본문 바로가기
자바 알고리즘

20. 학급회장 (HashMap)

by watergrace2u 2022. 9. 12.
반응형
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

댓글