본문 바로가기
코딩테스트 준비/백준

[백준] 20920번 - 영단어 암기는 괴로워 [Java]

by mwzz6 2025. 2. 20.

https://www.acmicpc.net/problem/20920

 

[백준] 20920번 - 영단어 암기는 괴로워 [Java]
[백준] 20920번 - 영단어 암기는 괴로워 [Java]
[백준] 20920번 - 영단어 암기는 괴로워 [Java]


1.  아이디어

 

Comparable을 이용한 정렬로 우선순위를 정하는 방식으로 해결할 수 있다.


2. 문제풀이

 

정렬에 단어의 빈도수가 필요하므로 Map으로 입력을 받아서 단어와 개수를 세줬다. 이후 각 Entry를 활용해 노드 클래스를 만들고 이를 우선순위에 맞게 정렬하는 방식으로 구현했다.


3. 코드

 

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

public class Main {

    private static class Node implements Comparable<Node> {
        String word;
        int cnt;

        public Node(String word, int cnt) {
            this.word = word;
            this.cnt = cnt;
        }

        public int compareTo(Node o) {
            if (this.cnt != o.cnt) return Integer.compare(o.cnt, this.cnt);
            if (this.word.length() != o.word.length()) return Integer.compare(o.word.length(), this.word.length());
            return this.word.compareTo(o.word);
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());

        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < N; i++) {
            String word = br.readLine();
            if (word.length() < M) continue;

            map.put(word, map.getOrDefault(word, 0) + 1);
        }

        List<Node> list = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            list.add(new Node(entry.getKey(), entry.getValue()));
        }
        Collections.sort(list);

        for (Node node : list) {
            sb.append(node.word).append("\n");
        }

        bw.write(sb.toString());
        bw.flush();
    }
}

4. 후기