JAVA 알고리즘

1181 - 단어 정렬

잡다한 저장소 2019. 9. 11. 15:42

https://www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1≤N≤20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

문제 풀이

N 개의 단어를 받아서

 

1. 길이가 짧은 것부터

2. 길이가 같으면 사전 순으로 정렬하여 출력하는 문제

 

중복된 단어의 경우 한번만 출력한다는 조건이 하나 더 있으므로 입력받은 문자를 Set 자료구조에 담아서 중복을 제거한 뒤에 ArrayList로 옮겨서 정렬

 

package ex01;

import java.util.*;
import java.io.*;
 

 
class BOJ1181 {
    public static void main(String args[]) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        
        // 중복 제거를 위해 set으로 먼저 input
        HashSet<String> set = new HashSet<String>();
 
        for(int i=0; i<N; i++) 
            set.add(br.readLine());
        
        // List 변환
        ArrayList<String> list = new ArrayList<String>(set);
 
        // Comparator 클래스를 통하여 custom 정렬
        // 길이에 따라서 먼저 정렬하고 길이가 같으면 사전순으로 정렬
        Collections.sort(list, new Comparator<String>() {
            public int compare(String v1, String v2) {
                if(v1.length() > v2.length()) 
                    return 1;
                else if(v1.length() < v2.length()) 
                    return -1;
                else
                    return v1.compareTo(v2);
            }
        });
 
        for(String s : list) 
            System.out.println(s);
    }
}