Post

[BaekJoon] #1157 - 단어 공부 [Java][C++][Python]

[BaekJoon] #1157 - 단어 공부 [Java][C++][Python]

문제 링크


1. 아이디어

대소문자를 구분하지 않고 단어에 가장 많이 쓰인 알파벳을 찾아 대문자로 출력하는 문제다. 대소문자를 한쪽으로 통일하면 알파벳은 26종뿐이므로 종류별 개수를 센 뒤 가장 큰 개수를 찾으면 된다. 다만 그 개수를 가진 알파벳이 둘 이상이면 ?를 출력해야 하므로 최댓값이 몇 번 나타나는지도 확인한다.


2. 코드

풀이 [Java][C++][Python]

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 s = br.readLine();
        int[] cnt = new int[26];

        for (char c : s.toCharArray()) {
            cnt[Character.toLowerCase(c) - 'a']++;
        }

        int maxIdx = -1;
        int max = 0;
        int maxCnt = 0;

        for (int i = 0; i < 26; i++) {
            if (cnt[i] > max) {
                maxIdx = i;
                max = cnt[i];
                maxCnt = 1;
            } else if (cnt[i] == max) {
                maxCnt++;
            }
        }

        if (maxCnt == 1) {
            System.out.println((char) (maxIdx + 'A'));
        } else {
            System.out.println("?");
        }
    }
}

maxIdx + 'A'는 int라서 char로 형변환해 문자로 출력했다.

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(0);
    cin.tie(0);

    string s;
    cin >> s;

    vector<int> cnt(26);
    for (char c : s) {
        cnt[tolower(c) - 'a']++;
    }

    int mx = *max_element(cnt.begin(), cnt.end());

    if (count(cnt.begin(), cnt.end(), mx) > 1) {
        cout << '?';
    } else {
        int idx = max_element(cnt.begin(), cnt.end()) - cnt.begin();
        cout << char(idx + 'A');
    }
}

std::max_element는 값이 아니라 이터레이터를 반환하므로 cnt.begin()을 빼서 인덱스로 바꿨고, char로 형변환해 문자로 출력했다.

1
2
3
4
5
6
7
8
9
10
import string
import sys

input = sys.stdin.readline

s = input().rstrip().upper()
cnt = [s.count(c) for c in string.ascii_uppercase]
mx = max(cnt)

print(string.ascii_uppercase[cnt.index(mx)] if cnt.count(mx) == 1 else "?")

string.ascii_uppercase의 문자마다 count로 횟수를 셌다. 알파벳이 26개라 문자열을 26번만 훑는다.


This post is licensed under CC BY 4.0 by the author.