백준 algorithm
백준 1157 - 단어공부
cosmohoo
2020. 3. 29. 12:03
반응형
=> arr : 알파벳을 하나씩 담을수 있는 26 크기의 배열이 필요하다
=> 각 index를 탐색하며 해당 알파벳이 나올때, 해당하는 arr 의 값을 올려준다.
A | B | C | ... | Z |
0 | 1 | 2 | ... | 25 |
=> 위의 배열은 각각의 알파벳을 지칭하고 원소값을 string에 나온 알파벳의 개수를 세어준다.
=> arr을 완성시킨 뒤, index 순서대로 올라가면 최대 크기를 가지고 있는 index 를 찾는다.
=> 이 경우 최대 크기를 가지고 있는 inde가 다수일 경우를 위해 rep 이라는 bool 변수를 사용했다.
=> 다수일 경우, ?를 출력한다.
=> 다수가 아닐 경우 해당하는 알파벳을 출력한다.
*** 이 코드는 보기엔 간단하지만, 효율성이 좋지 않다. 다른 사람들의 코드를 보면 0ms도 나온다...
본인은 8ms가 나온다.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
string s;
cin >> s;
int length= s.length();
int arr[26];
fill_n(arr, 26, 0);
for(int i=0; i<length; ++i)
{
if(s[i]>=65 && s[i]<=90) // Big Letter
arr[s[i]-'A']++;
else if(s[i]>=97 && s[i]<=122) // small Letter
arr[s[i]-'a']++;
}
int max=-1;
int maxIndex=0;
bool rep=false; // 중복이 없는 경우
for(int i=0; i<26; ++i)
{
if(arr[i]>max)
{
max=arr[i];
maxIndex=i;
rep=false;
}
else if(arr[i] == max)
{
max=arr[i];
rep=true;
}
}
if(rep)
{
cout << "?"<<'\n';
}
else
{ char c= maxIndex+'A';
cout << c<<'\n';
}
return 0;
}
반응형