본문 바로가기
백준

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

by naahy 2024. 3. 10.

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

 



방법이 생각나긴 했는데... 너무 오래 걸릴 것 같아서 다른 방법은 없을까 한참 고민했다.
그래도 일단 작성해서 돌려보긴 했는데 통과는 됐으나 역시 다른 사람들에 비해서 시간이 더 오래 걸림.
그래서 찾아보니 빈도수와 길이, 알파벳순 정렬을 굳이 따로 할 필요가 없었다. (난 따로 했음)

 

✨ 참고

https://propercoding.tistory.com/306

 

[백준] 20920번 : 영단어 암기는 괴로워 – JAVA [자바]

https://www.acmicpc.net/problem/20920 20920번: 영단어 암기는 괴로워 첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,0

propercoding.tistory.com

 


 

📍 getOrDefault(Object key, Object defaultValue)
map에서 해당 key가 존재한다면 그 key의 value를 반환하고, key가 존재하지 않으면 defaultValue를 반환하는 함수

Map<String, Integer> map1 = new HashMap<>();
map1.getOrDefault("key", 0);​


📍 Comparator.comparing()
비교하는 코드를 간략하게 작성할 수 있음

HashMap<String, Integer> map1 = new HashMap<>();
List<String> keys = new ArrayList<>(map1.keySet());

// key를 value 기준 오름차순으로 정렬
keys.sort(Comparator.comparing(map1::get));

 


 

풀이

1. 단어와 단어의 빈도수를 함께 저장할 Map 생성

2. 단어를 받아올 때마다 빈도수 증가

3. 모든 단어를 받고난 후 Map의 keySet 생성

4. 단어의 빈도수(map의 value)로 먼저 정렬 후 길이순, 알파벳순으로 정렬

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

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

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

        // 단어와 단어 빈도수 저장
        HashMap<String, Integer> dictionary = new HashMap<>();

        for (int i = 0; i < N; i++) {
            String word = br.readLine();

            if (word.length() < M) { continue; }

            int count = dictionary.getOrDefault(word, 0);
            dictionary.put(word, ++count);
        }

        List<String> words = new ArrayList<>(dictionary.keySet());
        words.sort((o1, o2) -> {
            if (dictionary.get(o1) != dictionary.get(o2)) { // 빈도수 정렬
                return dictionary.get(o2).compareTo(dictionary.get(o1));
            } else if (o1.length() != o2.length()) {    // 길이순 정렬
                return o2.length() - o1.length();
            } else {    // 알파벳순 정렬
                return o1.compareTo(o2);
            }
        });

        for (String word : words) {
            sb.append(word).append('\n');
        }

        System.out.println(sb);
    }
}

'백준' 카테고리의 다른 글

[백준 1012/자바] 유기농 배추  (0) 2024.03.19
[백준 15649/Java] N과 M(1)  (0) 2024.03.11
[백준 1003/Java] 피보나치 함수  (0) 2023.10.17
[백준 1874/Java] 스택 수열  (0) 2023.10.11
[백준 7785/Java] 회사에 있는 사람  (0) 2023.10.09

댓글