[백준/JAVA] 1181: 단어 정렬

농담곰·2023년 7월 13일

백준

목록 보기
8/33

[백준/JAVA] 1181: 단어 정렬

n개의 알파벳 단어가 입력으로 주어지면

  1. 길이가 짧은 것 우선
  2. 길이가 같다면 사전 순으로

정렬하는 문제이다. 이때 중복된 단어는 하나만 남기고 제거해야 한다.

단어 중복을 제거하기 위해 HashSet을 사용하였다 HashSet에서는 입력에서부터 중복된 단어는 덮어쓰여지기 때문에 자동으로 중복 제거를 할 수 있다.

그 후 HashSet을 ArrayList로 바꾼 후 Collections.sort()를 통해 정렬하였다. 조건이 주어져 있기 때문에 조건에 맞게 메서드를 오버라이딩하였다.

소스코드


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());
        HashSet<String> set = new HashSet<>();
        for(int i=0; i<n; i++)
        	set.add(br.readLine());
        
        ArrayList<String> list = new ArrayList<>(set);
        
        Collections.sort(list, new Comparator<String>() {
        	@Override
        	public int compare(String o1, String o2) {
        		if (o1.length() > o2.length()) return 1;
        		else if (o1.length() < o2.length()) return -1;
        		else return o1.compareTo(o2);
        	}
        });
        
        for(int i=0; i<list.size(); i++)
        	System.out.println(list.get(i));
	}
}

0개의 댓글