https://www.acmicpc.net/problem/20920
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. 후기
'코딩테스트 준비 > 백준' 카테고리의 다른 글
[백준] 14225번 - 부분수열의 합 [Java] (1) | 2025.02.21 |
---|---|
[백준] 17779번 - 게리맨더링 2 [Java] (0) | 2025.02.21 |
[백준] 20922번 - 겹치는 건 싫어 [Java] (0) | 2025.02.19 |
[백준] 21610번 - 마법사 상어와 비바라기 [Java] (0) | 2025.02.19 |
[백준] 2108번 - 통계학 [Java] (0) | 2025.02.19 |