OJ

[BOJ] 20920 영단어 암기는 괴로워 (JAVA)

P3PP4 2023. 2. 25. 10:00

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

 

20920번: 영단어 암기는 괴로워

첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단

www.acmicpc.net

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class Main {
	
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder();
    static StringTokenizer st;

    public static void main(String[] args) throws Exception {

        HashMap<String, Integer> map = new HashMap<>();
        st = new StringTokenizer(br.readLine(), " ");
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());

        for (int i = 0; i < N; i++) {

            String s = br.readLine();
            if (s.length() < M) continue;

            if (map.containsKey(s)) map.put(s, map.get(s) + 1);
            else map.put(s, 1);

        }

        PriorityQueue<Word> pq = new PriorityQueue<>();
        map.entrySet().forEach(x -> pq.offer(new Word(x.getKey(), x.getValue())));

        while (!pq.isEmpty()) {
            Word w = pq.poll();
            sb.append(w.s + "\n");
        }

        System.out.print(sb.toString());

    }

    static class Word implements Comparable<Word> {
        String s;
        int cnt;

        public Word (String s, int cnt) {
            this.s = s;
            this.cnt = cnt;
        }

        @Override
        public int compareTo (Word o) {
            if (this.cnt == o.cnt) {
                if (this.s.length() == o.s.length()) return this.s.compareTo(o.s);
                return o.s.length() - this.s.length();
            }
            return o.cnt - this.cnt;
        }
    }

}