카테고리 없음

[백준] 1157 : 단어 공부(JAVA)

송테이토 2022. 10. 11. 20:02

단어 공부

문제

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

입력

첫째 줄에 알파벳 대소문자로 이루어진 단어가 주어진다. 주어지는 단어의 길이는 1,000,000을 넘지 않는다.

출력

첫째 줄에 이 단어에서 가장 많이 사용된 알파벳을 대문자로 출력한다. 단, 가장 많이 사용된 알파벳이 여러 개 존재하는 경우에는 ?를 출력한다.

예제 입력 1

Mississipi

예제 출력 1

?

예제 입력 2

zZa

예제 출력 2

Z

예제 입력 3

z

예제 출력 3

Z

예제 입력 4

baaa

예제 출력 4

A

시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율

2 초 128 MB 190694 75505 60042 39.398%

시간 초과 코드

package Day1010;

import java.util.Arrays;
import java.util.Scanner;

public class B1157 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine().toUpperCase();
		sc.close();

		int cnt = 0;
		char result = 0;
		int[] arr = new int[str.length()]; // 각 글자가 몇 번 반복됐는지 배열에 넣기

		// 만약 단어가 한글자면 그대로 출력
		if (str.length() == 1) {
			System.out.println(str);
			// 아니라면 배열에 넣어서 중복되는 글자들 비교하기
		} else {
			// 중복된 글자 찾아서 몇 번 반복되는지 cnt 증가
			for (int i = 0; i < str.length(); i++) {
				for (int j = 0; j < i; j++) {
					if (str.charAt(i) == str.charAt(j)) {
						result = str.charAt(i);
						cnt++;
					}
				}
				// System.out.println(str.charAt(i) + " 몇 번? : " + cnt);
				// 각 단어가 몇 번 반복됐는지 배열에 넣기
				arr[i] = cnt;
				cnt = 0;
			}

			// 내림차순으로 정리해서 가장 큰 수가 두번 이상 반복된다면 ? 출력
			Arrays.sort(arr);
			for (int i = arr.length - 1; i >= 0; i--) {

				if (arr[arr.length - 1] == arr[arr.length - 2]) {
					result = '?';
				}
			}

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

그렇다. 풀면서도 내 코드가 굉장히 비효율적이라는 것을 느꼈다.

알파벳 배열을 이용해서 다시 풀자

코드

package Day1010;

import java.util.Scanner;

public class B1157 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine().toUpperCase(); // 모든 문자 대문자로 바꿔주기
		sc.close();

		int[] arr = new int[26]; // 알파벳 배열 선언
		int max = 0; // 최대 몇 번 반복하는지
		char result = 0; // 결과

		// 사용된 알파벳의 배열에 1씩 증가시킨다.
		for (int i = 0; i < str.length(); i++) {
			arr[str.charAt(i) - 65]++; // 65는 'A'

			// 배열의 최대값 구하기
			if (max < arr[str.charAt(i) - 65]) {
				max = arr[str.charAt(i) - 65];
				result = str.charAt(i);

				// 만약 최대값이 중복이라면 ? 출력
			} else if (max == arr[str.charAt(i) - 65]) {
				result = '?';
			}
		}
		System.out.println(result);
	}

}