Algorithm/[BOJ] - JAVA

[백준] 1181 : 단어 정렬 JAVA 풀이

Codew 2022. 5. 29. 18:08

1. 단어의 개수 N을 입력받는다.

2. N개의 단어를 입력받고, 그 단어가 처음 입력된 것이라면 ArrayList에 추가한다.

    -> 처음엔 일반 배열을 생성하고, 처음 입력된 단어일 때만 배열에 저장하려고 했다.

        그러나 for문으로 하다보니 배열의 중간이 비는 상황이 발생해서 ArrayList로 변경했다.

3. 길이가 짧은 순으로 정렬하고 길이가 같으면 사전 순으로 정렬한다.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.ArrayList;

public class Main{
    public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // N개의 단어를 입력받음
        int N = Integer.parseInt(br.readLine());
        // 입력받은 단어를 저장할 ArrayList를 생성
        ArrayList<String> list = new ArrayList<String>();
        
        for(int i=0;i<N;i++){
        // 단어를 입력받음
        	String tmp =  br.readLine();
        	// list에 없는 단어일 때만 새로 추가함
        	if(!list.contains(tmp)) {
        		list.add(tmp);
        	}
        }
        
        list.sort((o1, o2)->{
			// 단어의 길이가 같다면
            if(o1.length()==o2.length()){
            	// 사전순으로 정렬
                return o1.compareTo(o2);
            }
            // 단어의 길이가 다르다면
            else{
            	// 단어의 길이순으로 정렬
                return Integer.compare(o1.length(),o2.length());
            }
        });
        
        // 정렬된 리스트를 출력함
        for(int i=0;i<list.size();i++) {
        	System.out.println(list.get(i));
        }
    }
}