본문 바로가기
Baekjoon

[백준] 1157번 단어 공부 (Java)

by Chaewon Park 2024. 1. 31.

https://www.acmicpc.net/problem/1157

 

1157번: 단어 공부

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

www.acmicpc.net


문제

 

알고리즘

 

1. 26개의 알파벳이 몇 번 나왔는지 저장할 수 있는 배열 생성한다.

 

2. String str 에 입력받는다.

 

3. for문을 돌면서 str.charAt(i)로 배열에 +1을 해준다.

    * 이때, 아스키코드 필요! 소문자면 - 'a'를, 대문자면 - 'A'를 해준다.

 

4. 배열에 저장되어 있는 수를 비교하면서 출력할 ch에 저장한다.

    * 출력할 때는 배열의 index + 'A' 를 해주면 된다.

 

 

나는 처음에 int maxCnt 라는 변수를 만들어서 max가 현재 몇개인지도 체크하고 그 max의 index를 저장하는 int maxIndex도 생성했었는데 바보였다. 그냥 4번처럼 char maxCh를 생성하고 max와 같으면 ?를 저장하고 아니면 알파벳을 저장하면 됐었다!

 

풀이
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String str = br.readLine();
        br.close();

        int[] arr = new int[26];
        int index=0;

        for(int i=0; i<str.length(); i++){
            char c = str.charAt(i);
            if(c >= 97 && c <= 122) {
                index = c-97;
            }
            if(c >= 65 && c <= 90) {
                index = c-65;
            }
            arr[index]++;
        }

        int max = arr[0];
        char maxChar = 'A';

        for(int j=1; j<arr.length; j++){
            if(max == arr[j]) {
                maxChar = '?';
            }
            if(max < arr[j] ) {
                max = arr[j];
                maxChar = (char)(arr[j] + 65);
            }
        }

        bw.write(maxChar);
        bw.flush();
        bw.close();
    }
}