본문 바로가기

알고리즘/백준

[백준] 1157 - 단어 공부 (JAVA/ 자바)

반응형

1157번 문제

 

1. Scanner를 이용한 방법

import java.util.Scanner;

public class Main{
public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int[] alpha = new int[26];

    String input = sc.next().toUpperCase();

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

    int max = -1;
    char ans = '?';

    for(int i=0; i<alpha.length; i++){
        if(max < alpha[i]){
            max = alpha[i];
            ans = (char)(i+65);
        }else if(max == alpha[i]){
            ans = '?';
        }
    }
    System.out.println(ans);
    sc.close();
    }
}

 

 

2. BufferedReader를 이용한 방법

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

public class Main{
public static void main(String[] args)throws IOException{

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int[] alpha = new int[26];

    String input = br.readLine().toUpperCase();

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

    int max = -1;
    char ans = '?';

    for(int i=0; i<alpha.length; i++){
        if(max < alpha[i]){
            max = alpha[i];
            ans = (char)(i+65);
        }else if(max == alpha[i]){
            ans = '?';
        }
    }
    System.out.println(ans);
    br.close();
    }
}

 

대, 소문자를 구분하지 않는 상황에서 출력 시에는 알파벳을 대문자로 출력한다는 점에서 toUpperCase()를 이용해 입력된 문자를 대문자로 변형한 후에 ASCII 코드의 'A' 문자에 해당되는 65를 빼주고, 해당되는 문자의 위치의 숫자를 증가시키고 MAX와 비교하고 자주 사용되는 문자는 다시 i에 65를 더해주어서 알파벳으로 바꿔서 출력해주면 된다.

 

 

이번 문제의 풀이 방법을 생각해내는 게 어려워서 다른 분의 해결방법을 참고하여 해결했다..

막상 보고나니 좀 더 고민해보면 좋았을걸이라는 생각도 든다..

 

출처 : https://jaejong.tistory.com/16

반응형