알고리즘 풀이/백준

[백준][Java] 1181번 단어 정렬

배게 2021. 6. 27. 00:50
728x90

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
 
 
public class Main {
        
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
    public static void main(String[] args) throws IOException{
        // HashSet으로 중복 제거한 후에, hs.toArray(배열)로 set에서 Array로 변환.
        // Comparator로 length/사전순 처리 컷
        
        int N = Integer.parseInt(br.readLine());
        HashSet<String> hs = new HashSet<>();
        for(int i=0; i<N; i++) {
            hs.add(br.readLine());
        }
        String[] strArr = new String[hs.size()];
        hs.toArray(strArr);
        
        Arrays.sort(strArr, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // TODO Auto-generated method stub
                if(o1.length()==o2.length()) {
                    return o1.compareTo(o2);
                }
                return o1.length()-o2.length();
            }
        });
        
        for (String string : strArr) {
            System.out.println(string);
        }
        
    }
}
cs