[코테4_1] 학급 회장(해쉬맵)

byeol·2022년 12월 4일
0

코딩테스트

목록 보기
24/42

✔️ 내 답-> HashMap 초기화 과정에서 누락한 값이 존재해서 발견하고 다시 품

import java.util.*;
import java.util.Map.Entry;

public class Main {
 public static String solution(String input){
	 int max=0;
	 String answer="";
	 HashMap<Character,Integer> map = new HashMap<>();
	 map.put('A',0);
	 map.put('B',0);
	 map.put('C',0);
	 for( char x: input.toCharArray()){
		 Set set2= map.entrySet();
		 map.put(x, map.get(x)+1);
		 System.out.println(set2);
	 }
	 for(char x: map.keySet()) {
		 System.out.println(x);
		 if(max<map.get(x)) {
			 max=map.get(x);
			 answer=Character.toString(x);
			 }
	 }
	 
	 return answer;
 
 }
 public static void main(String[] args){
  Scanner kb = new Scanner(System.in);
  int n = kb.nextInt();
  String input=kb.next();
  System.out.println(solution(input));
 }
}

0으로 초기화를 해놓았는데도 여기서는
map.put(x, map.get(x)+1);
이 부분에 문제가 있다는 것-> 그것은 바로 내가 넣은 String에 ED도 있는데 그걸 초기화해 놓지 않았다.

해 놓았더니 제대로 출력되었다.

✔️ 강의 조금 듣고 풀어본 결과
초기화를 map.put(x, map.getOrDefault(x,0)+1);이렇게 진행한다.
value값이 없는 null인 경우 0으로 하고 거기에 +1을 넣는다.
이 과정으로 인해서 초기화를 해놓는 코드가 간략해졌다.

import java.util.*;
import java.util.Map.Entry;

public class Main {
public static String solution(String input){
	 int max=0;
	 String answer="";
	 HashMap<Character,Integer> map = new HashMap<>();
	 for( char x: input.toCharArray()){		 
		 map.put(x, map.getOrDefault(x,0)+1);
	 }
	 for(char x: map.keySet()) {
		 if(max<map.get(x)) {
			 max=map.get(x);
			 answer=Character.toString(x);
			 }
	 }
	 
	 return answer;

}
public static void main(String[] args){
 Scanner kb = new Scanner(System.in);
 int n = kb.nextInt();
 String input=kb.next();
 System.out.println(solution(input));
}
}
profile
꾸준하게 Ready, Set, Go!

0개의 댓글