반응형
SMALL
# 기억할 부분
1. map.put ( x, map.getOrDefault(x, 0) + 1);
=> map.getOrDefault(x,0)
=> 만약 hashmap에 x 키가 존재하지 않는 경우, 일단 0 값을 반환!
존재할 경우, 해당 키의 값 반환!
2. map.keySet()
for(char key: map.keySet()) {
System.out.println(key + " " + map.get(key));
}
결과값:
A 3
B 2
C 5
=> 이런식으로 키 + 값 형식으로 나옴!
package Algorithm;
import java.util.*;
public class Main {
public char solution(int n,String s) {
char answer = ' ';
HashMap<Character,Integer> map = new HashMap<>();
for(char x:s.toCharArray()) {
map.put(x,map.getOrDefault(x, 0)+1);
}
int max = Integer.MIN_VALUE;
for(char key: map.keySet()) {
// System.out.println(x + " " + map.get(x));
if(max<map.get(key)) {
max = map.get(key);
answer = key;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
String str = kb.next();
System.out.print(T.solution(n,str));
}
}
반응형
LIST
'자바 알고리즘' 카테고리의 다른 글
백준 9012번: 괄호 - StringBuilder 잘 활용하기(cf. sb.deleteCharAt(i)) (0) | 2024.11.17 |
---|---|
21. 아나그램(해쉬) (0) | 2022.09.13 |
19. 연속된 자연수의 합 (수학) (0) | 2022.08.10 |
18. 연속된 자연수의 합 (0) | 2022.08.09 |
17. 연속 부분 수열 (sliding window + 복합) (0) | 2022.08.08 |
댓글