[Java][백준] #1157 - 단어 공부

배수연·2024년 2월 26일

algorithm

목록 보기
7/45

🔗 백준 1157 - 단어 공부

문제

알고리즘 분류

  • 구현
  • 문자열

풀이

  • IDEA
    (1) 알파벳의 개수(26)만큼 int 배열을 생성해 각 알파벳이 입력된 횟수를 저장한다.
    (2) 이 때, 배열의 인덱스는 알파벳 - 65('A'의 아스키코드 값)이다.
    (3) 최댓값이 든 배열의 인덱스 + 65를 출력한다.

  • 주의할 점
    (1) 문제에서는 대문자와 소문자를 구별하지 않는다.
    (2) 출력할 때는 대문자로 출력한다.

1. 입력

  • 나는 처음에 대문자와 소문자를 구별해서 넣는 줄 알고 한참 노려봤는데, UpperCase로 받아 모두 대문자로 처리하면 된다. 문제를 잘 읽자..
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine().toUpperCase();
        int[] alphabets = new int[26];

        for(int i = 0; i<input.length(); i++){
            int alphabet = input.charAt(i);
            alphabets[alphabet-65]++;
        }

2. 최대로 사용된 단어 출력

  • 기본적으로 출력될 문자는 '?'로 저장해둔다.
  • 출력할 알파벳이 있다면 그 단어의 아스키코드를 저장하되, 출력할 알파벳이 여러 개라면 다시 '?'로 초기화
        int max = 0;
        int ascii = 63;
        for(int i = 0; i<26; i++){
            if(max < alphabets[i]){
                max = alphabets[i];
                ascii = i+65;
            } else if (max != 0 && max == alphabets[i]){
                ascii = 63;
            }
        }
        System.out.println((char)ascii);

전체 코드

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine().toUpperCase();
        int[] alphabets = new int[26];

        for(int i = 0; i<input.length(); i++){
            int alphabet = input.charAt(i);
            alphabets[alphabet-65]++;
        }
        int max = 0;
        int ascii = 63;
        for(int i = 0; i<26; i++){
            if(max < alphabets[i]){
                max = alphabets[i];
                ascii = i+65;
            } else if (max != 0 && max == alphabets[i]){
                ascii = 63;
            }
        }
        System.out.println((char)ascii);
    }
}

0개의 댓글