[백준] 1157번 - 단어 공부 [Java][C++]
[백준] 1157번 - 단어 공부 [Java][C++]
1. 문제 풀이
주어진 문자열에서 가장 많이 등장한 문자가 한 종류면 해당 문자를 출력하고 여러 종류면 ? 를 출력하면 되는 문제다. 대소문자를 구분하지 않으며 출력은 대문자로 해야 함에 유의해야 한다.
2. 코드
1. 구현 [Java]
cntArr 는 알파벳에 대한 카운팅 배열로 단어에서 각 알파벳의 등장 횟수를 기록했다.
maxIdx 는 가장 많이 등장한 알파벳의 위치로 A 를 더하면 실제 알파벳을 구할 수 있다. max 는 가장 많이 등장한 횟수이며, maxCnt 는 max 와 동일한 등장 횟수가 등장한 횟수로 ? 의 출력 여부를 판단하기 위해 활용했다.
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
30
31
32
33
34
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int[] cntArr = new int[26];
for (char c : str.toCharArray()) {
cntArr[Character.toLowerCase(c) - 'a']++;
}
int maxIdx = -1;
int max = 0;
int maxCnt = 0;
for (int i = 0; i < 26; i++) {
if (cntArr[i] > max) {
maxIdx = i;
max = cntArr[i];
maxCnt = 1;
} else if (cntArr[i] == max) {
maxCnt++;
}
}
if (maxCnt == 1) {
System.out.println((char) (maxIdx + 'A'));
} else {
System.out.println("?");
}
}
}
2. 구현 [C++]
똑같이 카운팅 배열을 활용하되 max_element 함수로 최대 등장 횟수를 구하고 count 함수로 최대 등장 횟수가 $1$ 번 이상 등장했는지 판단했다. $1$ 번만 등장했으면 카운팅 배열의 첫 포인터를 빼서 인덱스를 구했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> s;
vector<int> cntArr(26);
for (char c : s) {
cntArr[tolower(c) - 'a']++;
}
int mx = *max_element(cntArr.begin(), cntArr.end());
if (count(cntArr.begin(), cntArr.end(), mx) > 1)
cout << '?';
else {
int idx = max_element(cntArr.begin(), cntArr.end()) - cntArr.begin();
cout << char(idx + 'A');
}
}
3. 풀이 정보
1. 구현 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 248 ms | 22132 KB | 849 B |
2. 구현 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 8 ms | 3680 KB | 501 B |
This post is licensed under CC BY 4.0 by the author.