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

코드설명

구현 + 문자열 + 정렬 + 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;
	}
}

+ Recent posts