Algorithm/BOJ

[백준 알고리즘/BOJ/C++] 1157 단어 공부

pinevienna 2021. 1. 12. 12:14

 

 

영단어를 입력받아 가장 많이 사용된 알파벳을 찾는 문제

가장 많이 사용된 알파벳이 여러 개면 물음표를 출력한다

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;
 
int main(void) {
    string word;
    int alpha[26= { 0 };
    char result;
    int max = 0;
 
    cin >> word;
    
    for (int i = 0; i < word.size(); i++)
        word[i] = toupper(word[i]);
    
    for (int j = 0; j < word.size(); j++)
        alpha[(int)word[j] - 65+= 1;
 
    for (int j = 0; j < 26; j++) {
        if (alpha[j] == max) {
            result = '?';
        }
        else if (alpha[j] > max) {
            max = alpha[j];
            result = (char)(j + 65);
        }
    }
 
    cout << result;
}
cs

 

먼저 toupper를 사용하여 입력받은 단어를 대문자로 바꿔준다

문자를 int형으로 바꿔주면 아스키코드가 나오는데 대문자 A는 65다 (1씩 증가됨)

-65를 하면 0에서 25가 나오게 되는데, 그걸 배열의 주소값으로 사용하여 +1씩 count 해주면 된다