coding study/baekjoon

[java] 1181. 단어정렬

yeoonii 2023. 8. 13. 16:20
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());

        Set<String> words = new HashSet<>();  // 중복 제거를 위한 Set 사용

        for (int i = 0; i < N; i++) {
            words.add(br.readLine());  // 중복 제거된 단어 저장
        }

        List<String> sortedWords = new ArrayList<>(words);  // 중복 제거된 단어를 리스트로 변환
        Collections.sort(sortedWords, (a, b) -> {
            if (a.length() == b.length()) {
                return a.compareTo(b);  // 길이가 같으면 사전 순으로 정렬
            } else {
                return Integer.compare(a.length(), b.length());  // 길이가 짧은 것부터 정렬
            }
        });

        // 정렬된 단어 출력
        for (String word : sortedWords) {
            System.out.println(word);
        }

        br.close();
    }
}