자바 백준 9612번
실버 4
https://www.acmicpc.net/problem/9612
9612번: Maximum Word Frequency
Print out the word that has the highest frequency and its frequency, separated by a single space. If you get more than 2 results, choose only the one that comes later in the lexicographical order.
www.acmicpc.net
문제 보기

분류: 자료 구조, 문자열, 정렬, 해시를 사용한 집합과 맵
코드 보기
import java.util.Scanner; import java.util.HashMap; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // 단어 개수 입력 // 단어 빈도를 저장할 HashMap 선언 HashMap<String, Integer> wordFrequency = new HashMap<>(); for (int i = 0; i < n; i++) { // 한 줄에 하나의 단어를 입력받음 String word = sc.nextLine(); // HashMap에 단어를 키로 저장하고, 이미 존재하는 경우에는 빈도를 증가시킴 wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1); } int maxFrequency = 0; // 가장 높은 빈도 저장 변수 String mostFrequentWord = ""; // 가장 빈도가 높은 단어 저장 변수 for (HashMap.Entry<String, Integer> entry : wordFrequency.entrySet()) { if (entry.getValue() > maxFrequency || (entry.getValue() == maxFrequency && entry.getKey().compareTo(mostFrequentWord) > 0)) { // 만약 현재 단어의 빈도가 최댓값보다 크거나, 빈도가 같으면서 렉시컬 순서상 나중에 나오는 경우 mostFrequentWord = entry.getKey(); // 가장 빈도가 높은 단어 업데이트 maxFrequency = entry.getValue(); // 최댓값 업데이트 } } System.out.println(mostFrequentWord + " " + maxFrequency); // 결과 출력 } }
'공부하기 > 백준' 카테고리의 다른 글
[Java] 백준 풀기 5586 - JOI와 IOI (2) | 2023.10.17 |
---|---|
[Java] 백준 풀기 16499 - 동일한 단어 그룹화하기 (1) | 2023.10.14 |
[Python] 백준 풀기 1764 - 듣보잡 (0) | 2023.10.12 |
[Python] 백준 풀기 7785 - 회사에 있는 사람 (0) | 2023.10.11 |
[Python] 백준 풀기 19532 - 수학은 비대면강의입니다 (0) | 2023.10.09 |