본문 바로가기
Java/AlgorithmPS

백준) 단어 공부(1157번)

by NH_club 2023. 9. 17.
 

1157번: 단어 공부

알파벳 대소문자로 된 단어가 주어지면, 이 단어에서 가장 많이 사용된 알파벳이 무엇인지 알아내는 프로그램을 작성하시오. 단, 대문자와 소문자를 구분하지 않는다.

www.acmicpc.net

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String word = bf.readLine().toUpperCase();
        int[] alphabet = new int[26];
        int max = 0;
        char result = 0;

        for (int i = 0; i < word.length(); i++) {
            alphabet[word.charAt(i) - 'A'] += 1;
        }

        for (int i = 0; i < 26; i++) {
            if (alphabet[i] > max) {
                max = alphabet[i];
                result = (char)(i+'A');
            } else if (alphabet[i] == max) {
                result = '?';
            }
        }

        System.out.println(result);
    }

}

배운 점:

최빈 값을 알아내는 간단한 알고리즘.

아스키 코드를 이용한 char 활용법.