백준 1302

hong030·2023년 2월 26일
0
post-thumbnail
  • 실버 4단계 문제

풀이)
key 값은 중복되지 않고, key의 개수(value)만 바꿔주는 형식을 사용하기 위해 hashmap을 사용했다.

value가 같은 key 값 중에선 알파벳 순으로 앞에 오는 key를 뽑기 위해, hashmap을 정렬해주었다.

for 문을 돌려 가장 value가 큰 값을 찾고 그의 key 값을 출력했다.

내 코드)

import java.io.*;
import java.util.*;

public class Backjoon1302 {
	public static void main(String[]args) throws IOException{
		
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(bf.readLine());
		HashMap<String, Integer> table = new HashMap<String, Integer>();
		for(int i=0;i<N;i++) {
			String str = bf.readLine();
			if(table.containsKey(str)) {
				table.put(str, table.get(str)+1);
			}
			else
				table.put(str, 1);
		}
		
		Map<String, Integer> sortedTable = new TreeMap<>(table);
		//System.out.println(sortedTable);
		int max = 0;
		String ans = null;
		for (Map.Entry<String, Integer> pair : sortedTable.entrySet()) {
			if(pair.getValue() > max) {
				max = pair.getValue();
				ans = pair.getKey();
			}
		}
		
		System.out.println(ans);
	}
}

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글