Baekjoon Online Judge
문제
영어에서는 어떤 글자가 다른 글자보다 많이 쓰인다. 예를 들어, 긴 글에서 약 12.31% 글자는 e이다.
어떤 글이 주어졌을 때, 가장 많이 나온 글자를 출력하는 프로그램을 작성하시오.
입력
첫째 줄부터 글의 문장이 주어진다. 글은 최대 50개의 줄로 이루어져 있고, 각 줄은 최대 50개의 글자로 이루어져 있다. 각 줄에는 공백과 알파벳 소문자만 있다. 문장에 알파벳은 적어도 하나 이상 있다.
출력
첫째 줄에 가장 많이 나온 문자를 출력한다. 여러 개일 경우에는 알파벳 순으로 앞서는 것부터 모두 공백없이 출력한다.
예제 입력 | 예제 출력 |
english is a west germanic language originating in england and is the first language for most people in the united kingdom the united states canada australia new zealand ireland and the anglophone caribbean it is used extensively as a second language and as an official language throughout the world especially in common wealth countries and in many international organizations |
a |
baekjoon online judge | eno |
abc a | a |
abc ab |
ab |
amanda forsaken bloomer meditated gauging knolls betas neurons integrative expender commonalities latins antidotes crutched bandwidths begetting prompting dog association athenians christian ires pompousness percolating figured bagatelles bursted ninth boyfriends longingly muddlers prudence puns groove deliberators charter collectively yorks daringly antithesis inaptness aerosol carolinas payoffs chumps chirps gentler inexpressive morales |
e |
풀이
#include <iostream>
using namespace std;
int alpha[26] = {0};
int main() {
string s;
int big = -1;
while (cin >> s) {
for (int i = 0; i < s.length(); i++) {
int idx = (int)(s[i] - 'a');
alpha[idx]++;
// 가장 많이 나온 글자가 나온 횟수
if (alpha[idx] > big)
big = alpha[idx];
}
}
// 출력
for (int i = 0; i < 26; i++) {
if (alpha[i] == big)
cout << (char)(i + 'a');
}
return 0;
}
알파벳 소문자의 수만큼의 크기를 가진 alpha[] 배열을 생성해서 0으로 초기화했다. ahlpha 배열의 각 인덱스는 해당하는 소문자가 있고, 각 익덱스에 저장된 수는 그 소문자가 등장한 횟수를 의미한다.
while(cin >> s)로 입력값이 존재하는 동안에만 반복하도록 하였다. 그리고 while문 안에 s의 길이만큼 반복하는 for문을 넣었으며, for문은 s의 철자들을 확인한 뒤 해당되는 alpha 부분의 값을 증가시킨다. 만약 증가된 값이 big보다 크다면 big에 그 숫자를 저장했다.
big이 가장 많이 나온 글자가 나온 횟수이므로 alpha[i]의 값 중 big과 같은 값을 찾아 출력했다. 이때 (char)(i + 'a')를 통해 알파벳을 출력했는데 i는 1씩 증가하는 수이므로 출력값도 자연스럽게 알파벳 순으로 앞서는 것부터 출력된다.
'백준 > C++' 카테고리의 다른 글
[Baekjoon/C++] 1384번 - 메시지 (0) | 2022.05.30 |
---|---|
[Baekjoon/C++] 1373번 - 2진수 8진수 (0) | 2022.05.30 |
[Baekjoon/C++] 1362번 - 펫 (0) | 2022.05.21 |
[Baekjoon/C++] 1357번 - 뒤집힌 덧셈 (0) | 2022.05.21 |
[Baekjoon/C++] 1356번 - 유진수 (0) | 2022.05.21 |