본문 바로가기
내가 겪은 정보

다중정렬

by 배성인 2023. 4. 28.

문제는 백준 1181번 단어정렬

조건은 길이가 짧은것부터 정렬 길이가 같으면 사전 순으로 정렬

13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours

예제 출력 1 복사

i
im
it
no
but
more
wait
wont
yours
cannot
hesitate

----------------------------------

코드는 

import java.io.*;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        try {
            int num = Integer.parseInt(br.readLine());
            String[] strings = new String[num];
            for (int i = 0; i < num; i++) {
                strings[i] = br.readLine();
            }

            Arrays.stream(strings).distinct()
                                .sorted(
                                    new Comparator<String>() {
                                        @Override
                                        public int compare(String string1, String string2) {
                                            if(string1.length() != string2.length()) {
                                                int num = string1.length() - string2.length();
                                                return num;
                                            }

                                            else return string1.compareTo(string2);
                                        }
                                    }
                                )
                                .forEach(System.out::println);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}