programming
[c++] 백준 1157
Mysteryu
2023. 5. 30. 22:25
제출 코드
#include <iostream>
int main() {
std::string s;
std::cin >> s;
int alpha[26] = { 0 };
for (int i = 0; i < s.length(); i++) {
if ((int(s[i]) >= 97) && (int(s[i]) <= 122)) { //특정 문자가 소문자일시
alpha[int(s[i]) - 97] += 1;
}
else if ((int(s[i]) >= 65) && (int(s[i]) <= 90)) { //특정 문자가 대문자일시
alpha[int(s[i]) - 65] += 1;
}
}
int max = 0;
int equal_count = 0;
int num = 0;
for (int j = 0; j < 26; j++) {
if (max < alpha[j]) {
max = alpha[j];
equal_count = 0;
num = j;
}
else if (max == alpha[j]) {
++equal_count;
}
}
if (equal_count == 0)
std::cout << char(num + 65) << "\n";
else
std::cout << "?" << "\n";
}
이후에 조금 더 효율적인 코드가 있을 것 같아서 다른 블로그를 참고한 후에 두번째 for 문에서 아예 출력되는 문자를 구할 수 있을 것 같아서 수정 후 다시 제출하니 통과하였다만 시간은 오히려 더 오래 걸렸다. 위의 소스코드는 40ms가 걸린거에 비해 아래 코드는 48ms가 걸린 걸 보니 코드 수가 짧다고 무조건 효율적인 것은 아닌 것 같다. 소스코드는 아래와 같다.
#include <iostream>
int main() {
std::string s;
std::cin >> s;
int alpha[26] = { 0 };
for (int i = 0; i < s.length(); i++) {
if ((int(s[i]) >= 97) && (int(s[i]) <= 122)) { //특정 문자가 소문자일시
alpha[int(s[i]) - 97] += 1;
}
else if ((int(s[i]) >= 65) && (int(s[i]) <= 90)) { //특정 문자가 대문자일시
alpha[int(s[i]) - 65] += 1;
}
}
int max = 0;
char result;
for (int j = 0; j < 26; j++) {
if (max < alpha[j]) {
max = alpha[j];
result = char(j + 65);
}
else if (max == alpha[j]) {
result = '?';
}
}
std::cout << result << "\n";
}