728x90
반응형
SMALL
단어 공부

풀이
- 문제 파악
- 각 문자에 대해 반복출현 숫자를 담는다.
- 담은 숫자를 비교하여 가장 큰 수를 출력한다.
- 가장 큰 수를 가진 문자열이 여러개인 경우 ?를 출력한다.
- 변수 생성
- 단어를 받을 문자열 변수 생성
- 코드 구현
package Simulation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; import java.io.*; public class SimulationP1157 { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); str = str.toUpperCase(); HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < str.length(); i++) { String x = str.charAt(i)+""; map.put(x, map.getOrDefault(x, 0) + 1); } int max =Integer.MIN_VALUE; String maxStr = ""; int maxCnt=0; for (Map.Entry<String, Integer> entry : map.entrySet()) { if(max < entry.getValue()){ max = entry.getValue(); maxStr = entry.getKey(); maxCnt=0; } else if (max == entry.getValue()) { maxCnt++; } } System.out.println(maxCnt>=1?"?":maxStr); } }
반례 (위 코드는 수정한 코드)
- ababccc
- a와 b에서 비교 후 break를 해버리는 예외적인 상황 발생
- break를 제거 하고 새롭게 출현한 maxStr이 있을 경우 maxCnt를 초기화 하여 조건에 맞을때만 증가하도록 변경
728x90
반응형
SMALL
'문제 풀이 > 백준 문제풀이' 카테고리의 다른 글
알고리즘 - 위상정렬 (0) | 2024.08.09 |
---|---|
[BOJ14501 - Java] 퇴사문제 DP로 풀이하기 (0) | 2024.07.28 |
[백준11047 - Java] 구현 - 주사위 굴리기 (1) | 2024.04.23 |
[백준11047 - Java] 동전 0 Greedy 알고리즘으로 풀 (1) | 2024.03.26 |
[백준12789-자바/우선순위큐] 도키도키 간식드리미 (0) | 2024.03.20 |