HashMap_제일 많이 등장한 알파벳 찾기
✅ 학급 회장을 뽑는데 후보로 기호 A, B, C, D, E가 있다. 제일 많이 나온 학생을 뽑을 것이다.
반드시 한 명의 학급회장이 선출되도록 투표결과가 나온다.
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
32
33
class Main {
public char solution(int n, char[] voteArr){
char answer= ' ';
int max=0;
HashMap<Character, Integer> map= new HashMap<>();
for(char c: voteArr){
map.put(c, map.getOrDefault(c, 0)+1);
}
for(char key: map.keySet()){
if(map.get(key)>max) {
max= map.get(key);
answer= key;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
String input= sc.next();
char [] voteArr= input.toCharArray();
System.out.print(T.solution(n, voteArr));
}
}
//⭐️input:
// 15
// BACBACCACCBDEDE
//⭐️output:
//C
🔵 ThingsILearned
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
32
33
34
HashMap<Character, Integer> map= new HashMap<>();
map.put('A', 1);
map.put('B', 3);
map.put('C', 5);
// map.get(key) //key값의 value를 받아온다.
map.get('A') //1
// map.getOrDefault(key, 0) //key값의 value를 받아오되, 값이 없다면 0이다.
map.getOrDefault('F', 0) //0
// map.containsKey(key)
boolean contains key= map.containsKey('A') //true
boolean contains key= map.containsKey('F') //false
boolean containsValue = map.containsValue(2); //false
boolean empty = map.isEmpty();
int size= map.size() //3
// map.remove (key)
map.remove('A')
for(char key: map.keySet()){
System.out.println(key);
}
for(Integer value: map.values()){
System.out.println(value);
}
for(Map.Entry<Character, Integer> entry: map.entrySet()){
System.out.println("key: " + entry.getkey() + "value: " + entry.getValue());
}
🟢 먼저 map의 key값을 정의하고, 맞으면 value를 증가시키는 방식
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
32
33
34
class Main {
public char solution(int n, char[] voteArr){
char answer= '0';
int max=0;
HashMap<Character, Integer> map= new HashMap<>();
map.put('A', 0);
map.put('B', 0);
map.put('C', 0);
map.put('D', 0);
map.put('E', 0);
for(char c: voteArr){
if(map.containsKey(c)){
int votes= map.get(c) + 1;
map.put(c, votes);
if(votes>max) {
max=votes;
answer= c;
}
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
String input= sc.nextLine();
char [] voteArr= input.toCharArray();
System.out.print(T.solution(n, voteArr));
}
}
This post is licensed under CC BY 4.0 by the author.