Java
[백준 20920] 영단어 암기는 괴로워 (JAVA)
iheeeee6-6
2023. 2. 22. 19:47
728x90
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
객체를 만들고, Map과 ArrayList를 사용하여 문제를 해결하였다.
Map의 키는 단어, 값은 단어가 나온 수를 넣는다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class Main {
static class Word {
int count;
String word;
Word(int count, String word) {
this.count = count;
this.word = word;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Word> arrlist = new ArrayList<>();
Map<String,Integer> map = new HashMap<>();
for(int i=0;i<n;i++) {
String str = br.readLine();
if(str.length()>=m) {
map.put(str,map.getOrDefault(str, 0)+1);
}
}
for(String str:map.keySet()) {
arrlist.add(new Word(map.get(str),str));
}
Collections.sort(arrlist,(w1,w2)->{
if(w1.count==w2.count) {
if(w1.word.length()==w2.word.length()) {
return w1.word.compareTo(w2.word);
}else {
return w2.word.length()-w1.word.length();
}
}else {
return w2.count-w1.count;
}
});
StringBuilder sb = new StringBuilder();
for(int i=0;i<arrlist.size();i++)
sb.append(arrlist.get(i).word).append("\n");
System.out.println(sb);
}
}