n개 문자열을 입력받은 후
위 정렬 조건에 따라 정렬하는 문제이다. 이때 길이가 m보다 짧은 단어는 저장하지 않는다.
입력 빈도를 카운트하기 위해 우선 HashMap에 저장한 후, key값만 list에 저장하여 Collections.sort를 통해 정렬하였다.
다중 정렬 조건이 주어졌기 때문에 compare 메서드를 오버라이딩하여 정렬 조건을 새로 정의하였다.
@Override
public int compare(String o1, String o2) {
if (map.get(o1) == map.get(o2)) {
if (o1.length() == o2.length()) return o1.compareTo(o2);
else return o2.length() - o1.length();
}
else return map.get(o2) - map.get(o1);
}
map.get()으로 해당 key값의 value(빈도수)를 비교한다.
import java.util.*;
import java.io.*;
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());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
HashMap<String, Integer> map = new HashMap<>();
for(int i=0; i<n; i++) {
String word = br.readLine();
if (word.length() < m)
continue;
if (!map.containsKey(word))
map.put(word, 1);
else
map.put(word, map.get(word)+1);
}
ArrayList<String> list = new ArrayList<>(map.keySet());
/*
* 1. 자주 나오는 단어일수록 앞에 배치한다.
* 2. 해당 단어의 길이가 길수록 앞에 배치한다.
* 3. 알파벳 사전 순으로 앞에 있는 단어일수록 앞에 배치한다.
*/
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (map.get(o1) == map.get(o2)) {
if (o1.length() == o2.length()) return o1.compareTo(o2);
else return o2.length() - o1.length();
}
else return map.get(o2) - map.get(o1);
}
});
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(System.out));
for (int i=0; i<list.size(); i++)
bw.write(list.get(i)+"\n");
bw.flush();
}
}