N번의 입력하는 동안
가장 많이 나온 문자열을 출력합시다
중복이라면
사전순서로 먼저 나오는 것을 출력합시다
코드입니다
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
HashMap<String, Integer> map = new HashMap<String, Integer>();
int n = scan.nextInt();
scan.nextLine(); // 버퍼 비우기
String maxKey = null;
int maxValue = Integer.MIN_VALUE;
for (int i=0; i<n; i++) {
String str = scan.nextLine();
map.put(str, map.getOrDefault(str, 0) + 1);
if (map.get(str) > maxValue || (map.get(str) == maxValue && str.compareTo(maxKey) < 0)) {
maxValue = map.get(str);
maxKey = str;
}
}
System.out.print(maxKey);
}
}
주의해야할 부분은
scan.nextInt()다음에
scan.nextLine()을 하고싶으면
중간에 버퍼 지우기용
scan.nextLine()한번을 넣어줘야합니다
'백준 문제풀기 > JAVA' 카테고리의 다른 글
[백준 15439 JAVA 자바] 베라의 패션 (0) | 2023.08.26 |
---|---|
[백준 14916 JAVA 자바] 거스름돈 (0) | 2023.08.26 |
[백준 14681 JAVA 자바] 사분면 고르기 (0) | 2023.08.26 |
[백준 14492 JAVA 자바] 부울행렬의 부울곱 (0) | 2023.08.26 |
[백준 14425 JAVA 자바] 문자열 집합 (0) | 2023.08.26 |