본문 바로가기
알고리즘/백준

백준 1157번 단어 공부 자바 java

by 클로드 2021. 4. 15.
반응형

문제

 

풀이

 

대문자 A ~ Z 알파벳 개수를 세기 위한 26개 배열을 만들고

char형 'A'의 값의 int형 값은 65

입력받은 문자열의 문자를 char형 → int형으로 변환해서 해당 배열에 인덱스의 값을 +1을 함

 

코드

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int[] strCount = new int[26]; //A ~ Z 알파벳 26개
        int max = 0;
        int maxIndex = 0;

        str = str.toUpperCase();
        
        //알파벳 수 계산
        for (int i = 0; i < str.length(); i++) {
            strCount[(int)str.charAt(i) - 65]++; // char A = 65
        }
        
        //가장 많이 사용된 알파벳 찾기
        for (int i = 0; i < strCount.length; i++) {
            if (max < strCount[i]) {
                max = strCount[i];
                maxIndex = i;
            } else if (max == strCount[i]) {
                maxIndex = -1;
            }
        }

        if (maxIndex == -1) {
            System.out.println("?");
        } else {
            System.out.println((char)(maxIndex + 65));
        }
    }
}

 

출처

www.acmicpc.net/problem/1157

반응형

댓글