https://www.acmicpc.net/problem/1157
1157번: 단어 공부
알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.
www.acmicpc.net
map 자료구조를 이용하는 문제입니다.
우선 문제부터 간단하게 요약하면,
알파벳 대소문자로 만들어진 단어가 주어지면, 단어에서 가장 많이 사용된 알파벳이 무엇인지 대문자로 출력해야 합니다.
<Solution>
우선 대소문자로 된 알파벳을 대문자 혹은 소문자 하나로 통일한 후,
각각의 알파벳의 갯수를 map자료구조로 counting한 후, 결과를 도출하면 됩니다.
실제 구현은 아래와 같습니다.
#include <iostream>
#include <cctype>
#include <algorithm>
#include <map>
using namespace std;
int main(){
string s;
int same_flag = 0;
cin >> s;
transform(s.begin(), s.end(), s.begin(), ::tolower);
map<char, int> s_map; // todo : study unoredered map..
for(int i = 0; i < s.length() ; i++){
s_map[s[i]]++;
}
int initial_t = -1;
char ans;
for(map<char, int>::iterator t = s_map.begin(); t != s_map.end(); ++t){
if(t->second > initial_t){
initial_t = t->second;
same_flag = 0;
ans = t->first;
}
else if(t->second == initial_t){
same_flag = 1;
}
else{
continue;
}
}
if (same_flag == 0){
cout << (char)(ans-32) << endl;
}
else{
cout << '?'<< endl;
}
}
반응형
'코딩테스트 > C++ 문제풀이' 카테고리의 다른 글
[백준] 숫자의 합 (0) | 2022.08.21 |
---|---|
[백준] 음계 (0) | 2022.08.21 |
[백준] 나머지 (0) | 2022.08.20 |
[백준] OX퀴즈 (0) | 2022.08.20 |
[백준] 별 찍기 - 2 (0) | 2022.08.20 |