ALGORITHM
백준 20920 영단어 암기는 괴로워 (Java)
공부하는_다온
2023. 5. 23. 21:50
1. 문제 링크
20920번: 영단어 암기는 괴로워
첫째 줄에는 영어 지문에 나오는 단어의 개수 $N$과 외울 단어의 길이 기준이 되는 $M$이 공백으로 구분되어 주어진다. ($1 \leq N \leq 100\,000$, $1 \leq M \leq 10$) 둘째 줄부터 $N+1$번째 줄까지 외울 단
www.acmicpc.net
2. 문제 및 입출력예제
3. 문제 풀이
- 단어가 들어오면 길이가 M이 넘는지 확인한다.
- 단어와 횟수를 Word로 해서 list에 넣었다.
- Word에서는 단어가 나타난 개수 우선으로 비교하고, 길이를 비교한다.
- list를 정렬하고 그 안의 단어를 출력한다.
4. 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
public class Main {
static class Word implements Comparable<Word>{
String word;
int cnt;
public Word(String word, int cnt) {
super();
this.word = word;
this.cnt = cnt;
}
@Override
public int compareTo(Word o) {
if(this.cnt != o.cnt) {
return o.cnt - this.cnt;
}
if(this.word.length() != o.word.length()) {
return 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));
StringBuilder sb = new StringBuilder();
HashMap<String, Word> map = new HashMap<>();
List<Word> list = new ArrayList<>();
String[] split = br.readLine().split(" ");
int N = Integer.parseInt(split[0]);
int M = Integer.parseInt(split[1]);
for(int i=0;i<N;i++) {
String str = br.readLine();
if(str.length()>=M) {
if(map.containsKey(str)) {
map.get(str).cnt++;
}
else {
Word word = new Word(str, 1);
map.put(str, word);
list.add(word);
}
}
}
Collections.sort(list);
for(Word w: list) {
sb.append(w.word).append("\n");
}
System.out.println(sb);
}
}