문제 링크
성능 요약
메모리: 14544 KB, 시간: 136 ms
분류
구현(implementation), 문자열(string)
문제 설명
Pirates talk a funny way. They say word where the letters are repeated more than they need to be. We would like know which letter appears the most frequently in a Pirate word.
For example: In the word “arrrrrghh”, the letter “r” appears 5 times while “h” appears twice.
Write a program that reads a pirate word from the terminal and writes the letter that occurs most frequently.
It is guaranteed that only one letter is the most repeated. That is, words like “aipo” won’t appear because no single letter wins.
입력
The input will consist of two lines.
The first line will contain the size of the word and the second the word to process.
The word will only contain lowercase letters from a to z. The size of the word will be at most 1000 characters. No spaces or other symbols will appear.
출력
Print a single line with the character that appears the most and the number of occurrences.
문제풀이
해당 문제는 몇개의 문자가 들어갈지 입력받은 후 문자열을 입력하여 해당 문자열에 똑같은 문자가 몇개가 있는지 출력하는 문제이다.
문자열을 배열에 입력받은 후 미리 알파벳 순서대로 입력해둔 배열을 이용하여 같을 경우에는 또 다른 배열에 숫자를 더하여 저장해줬다.
이런 방식으로 입력받은 배열을 전부다 확인하고 그 중 최대값을 찾아 출력해줬다.
처음에는 리스트형식으로 바꿔 인덱스값을 찾아보려 했지만 indexOf를 사용해도 찾을 수 없어서 노가다로 문제를 풀었다.
문제를 다 풀고보니 아스키 코드를 이용해서도 쉽게 풀이가 가능할것같다.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
static char arr[]; // 입력받을 문자열을 저장하는 배열
static int Max = 0; // Max는 최대값을 저장해줄 변수
static char[] Alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; // Alphabet에 알파벳 순서대로 저장
static int[] count = new int[26]; // 알파벳 순서대로 몇번 나왔는지 저장할 배열
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine()); // 문자 개수 입력
String str = br.readLine(); // str에 문자열 입력
arr = new char[N]; // 입력받을 문자열 길이만큼 배열을 생성해줌
for(int i = 0; i < N; i++) {
arr[i] = str.charAt(i); // chatAt를 통해 str의 문자열을 문자 단위로 끊어서 배열에 저장
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < 26; j++) {
if(arr[i] == Alphabet[j]) { // 입력받은 문자와 알파벳이 같은지 확인
count[j] += 1; // 같다면 미리 선언해둔 count배열에 1을 더해줌
break; // 같은게 확인되었기 때문에 뒤에 포문은 생략
}
}
}
for(int i = 0; i < 26; i++) {
if(Max < count[i]) { // 최대값보다 큰지 확인
Max = count[i]; // 최대값 갱신
}
}
for(int i = 0; i < 26; i++) {
if(Max == count[i]) { // 최대값인지 확인
System.out.printf("%c %d", Alphabet[i], count[i]); // 최대값을 출력
}
}
}
}
'백준 문제풀이' 카테고리의 다른 글
[Baekjoon 1759] 암호 만들기 - JAVA (0) | 2022.11.29 |
---|---|
[Baekjoon 5635] 생일 - JAVA (0) | 2022.11.22 |
[Baekjoon 10026] 적록색약 - JAVA (0) | 2022.10.04 |
[Baekjoon 1927] 최소 힙 - JAVA (0) | 2022.08.16 |
[Baekjoon 15240] Paint bucket - JAVA (0) | 2022.07.03 |