https://www.acmicpc.net/problem/20920
코드설명
구현 + 문자열 + 정렬 + hashmap 을 사용하여 해결합니다.
1. HashMap을 순회하는 코드입니다.
for(Map.Entry<String, Integer> entry : hashmap.entrySet()){
nodeList.add(new Node(entry.getKey(), entry.getValue()));
}
2. 문자열의 사전순을 비교할때는 compareTo() 를 통해 진행합니다.
this.word.compareTo(other,word) > 0 이라면
this.word의 사전순이 더 크므로 this.word - other.word 사전순 값이 > 0 입니다.
그러므로 사전순값으로 더 빠르게해야하므로 return 1을 통해서 순서를 바꿔줍니다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class Main {
public static int N, M;
public static String[] arr;
public static HashMap<String, Integer> hashmap;
public static ArrayList<Node> nodeList = new ArrayList<>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
hashmap = new HashMap<String, Integer>();
arr = new String[N];
for(int i=0;i<N;i++) {
st = new StringTokenizer(br.readLine());
arr[i] = st.nextToken();
if(arr[i].length() < M) continue;
hashmap.put(arr[i], hashmap.getOrDefault(arr[i], 0) + 1);
}
for(Map.Entry<String, Integer> entry : hashmap.entrySet()) {
// System.out.println(entry.getValue()+" "+entry.getKey());
nodeList.add(new Node(entry.getKey(), entry.getValue()));
}
Collections.sort(nodeList);
StringBuilder sb = new StringBuilder();
for(int i=0;i<nodeList.size();i++) {
// System.out.println(nodeList.get(i).word);
sb.append(nodeList.get(i).word).append("\n");
}
System.out.println(sb);
}
}
class Node implements Comparable<Node>{
String word;
int cnt;
public Node(String word, int cnt) {
this.word = word;
this.cnt = cnt;
}
@Override
public int compareTo(Node other) {
if(this.cnt < other.cnt) {
return 1;
}else if(this.cnt == other.cnt) {
if(this.word.length() < other.word.length()) {
return 1;
}else if(this.word.length() == other.word.length()) {
if(this.word.compareTo(other.word) > 0) {
return 1;
}else if(this.word.compareTo(other.word) == 0) {
return 0;
}else {
return -1;
}
}else if(this.word.length() > other.word.length()) {
return -1;
}
}
else {
return -1;
}
return -1;
}
}
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2607 비슷한 단어 - 구현 + 문자열 JAVA (0) | 2023.08.07 |
---|---|
[백준] 19941 햄버거 분배 - 그리디(탐욕법, Greedy) JAVA (0) | 2023.08.07 |
[백준] 3109 빵집 - 그리디 + DFS JAVA (0) | 2023.08.01 |
[백준] 15591 MooTube (Silver) - 그래프 + DFS + BFS JAVA (0) | 2023.08.01 |
[백준] 2141 우체국- 그리디 + 수학(median, 중간값) JAVA (0) | 2023.07.24 |