Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

[백준 JAVA] 1157번 - 단어 공부 본문

오늘의 문제

[백준 JAVA] 1157번 - 단어 공부

jeongwon_ 2022. 6. 7. 11:02

문제: 

 

1157번: 단어 공부

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

www.acmicpc.net

 

약식 순서도:

1) 단어를 입력받아 대문자(혹은 소문자)로 변환 후 변수에 저장한다. (BufferedReader, toUpperCase, String)

2) 알파벳 개수(26) 크기의 int 배열을 생성한다. 

3) 문자열의 각 자리-65를 index로 하는 배열의 값을 1 증가시킨다. (문자가 A인 경우 65-65=0 번 index에 저장) *

4)  임의의 max 변수와 배열의 각 index의 값을 비교해 큰 값을 max에 저장한다. *

5) 배열의 값들을 비교해 같은 경우 '?'를, 다른 경우 해당 인덱스에 65를 더한 문자를 변수에 저장해 출력한다. (char, 형변환)

 

나의 답안 : 

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));
		String str = br.readLine().toUpperCase();
        
		int[] alpha = new int[26];

		for(int i=0; i<str.length(); i++) {
			if('A'<=str.charAt(i) && str.charAt(i)<='Z') {
				alpha[str.charAt(i)-65]++;
			}
		}
		int max=0;
		char result = ' ';
		for(int i=0; i<26; i++) {
			if(alpha[i]>max) {
				max=alpha[i];
				result = (char)(i+65);
			}
			else if(alpha[i]==max) {
				result = '?';
			}
		}

		System.out.println(result);
        br.close();
	}
}

index 값에 문자(str.charAt(i))를 이용함으로써 저장의 용이함은 물론, 배열에 저장된 알파벳의 위치=>알파벳으로 가져오는 문제를 쉽게 해결할 수 있었던 것이다..

도움받은 곳 : https://st-lab.tistory.com/64