Algorithm/BOJ
백준 1157번 C++
poopooreum
2023. 7. 21. 20:29
반응형
백준 1157번 단어 공부
https://www.acmicpc.net/problem/1157
1157번: 단어 공부
알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.
www.acmicpc.net


정답 코드
#include<iostream>
#include<string>
using namespace std;
string str;
int dat[125];
void find(char al);
int find2();
int max1 = 0;
int main() {
cin >> str;
char a = 'a';
char b = 'A';
int dx = 0;
for (int x = 0; x < 26; x++) {
find(a);
a += 1;
}
for (int x = 0; x < 26; x++) {
find(b);
b += 1;
}
for (int x = 97; x <= 124; x++) {
dat[x] = dat[x] + dat[x - 32];
}
for (int x = 97; x <=124; x++) {
if (max1 < dat[x]) {
max1 = dat[x];
dx = x;
}
}
int len=find2();
if (len == 1)
cout << "?";
if (len == 0)
cout << (char)(dx-32);
}
void find(char al) {
int b = 0, cnt = 0;
while (1) {
int res = str.find(al, b);
if (res == -1)
break;
int num = (int)al;
dat[num]++;
b = res + 1;
}
}
int find2() {
int cnt = 0;
for (int x = 97; x < 125; x++) {
if (max1 == dat[x])
cnt++;
}
if (cnt >= 2)
return 1;
else
return 0;
}
문제 풀이
카운팅 정렬을 이용하면 쉽게 풀 수 있습니다. 문장을 입력받은 후 반복문을 돌려서 각각의 문자를 숫자로 바꿔주어서 배열에 체크를 해주었습니다. 그리고 이 배열에서 최댓값을 구하여 그 문자를 출력하였습니다. 저는 소문자와 대문자를 나누었는데 그냥 문자에서 '0'을 빼시면 코드가 더 간결해질 것 같습니다.
반응형