[BaekJoon] 1181 단어 정렬

오태호·2022년 1월 1일
0

1.  문제 링크

https://www.acmicpc.net/problem/1181

2.  문제

요약

  • 알파벳 소문자로 이루어진 단어 여러 개를 길이가 짧은 순, 길이가 같으면 사전 순으로 정렬합니다.
  • 입력: 첫째 줄에는 단어의 개수가 주어지고 이후 줄부터는 단어가 하나씩 주어집니다.
  • 출력: 정렬된 단어들을 순서대로 출력합니다. 같은 단어가 여러 번 있다면 해당 단어는 한 번만 출력합니다.

3.  소스코드

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class Main {
    public String[] sort(int n, String[] words) {
        Arrays.sort(words, new Comparator<String>() {
            public int compare(String s1, String s2) {
                if(s1.length() == s2.length()) {
                    return s1.compareTo(s2);
                } else {
                    return s1.length() - s2.length();
                }
            }
        });
        return words;
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String[] words = new String[n];
		for(int i = 0; i < n; i++) {
			words[i] = br.readLine();
		}
		String[] result = new Main().sort(n, words);
        System.out.println(result[0]);
		for(int i = 1; i < result.length; i++) {
            if(!result[i - 1].equals(result[i])) {
                System.out.println(result[i]);
            }
		}
    }
}

4.  접근

  • 조건을 확인해보면 길이가 짧은 순으로 정렬하고 길이가 같다면 사전 순으로 정렬되도록 해야 하기 때문에, 우선 두 단어를 비교할 때, 단어의 길이가 같은지 다른지부터 확인하고 만약 다르다면 더 긴 단어가 정렬할 때 뒤로 가도록 조건을 설정합니다.
  • 만약 길이가 같다면, 사전 순으로 정렬되면 되기 때문에 두 단어를 비교할 때 사전 순으로 앞에 있는 것이 정렬할 때, 앞으로 올 수 있도록 조건을 설정합니다.
  • 출력할 때, 동일한 단어가 있다면 해당 단어는 한 번만 나올 수 있도록 정렬된 상태에서 가장 처음 나오는 단어만 출력하고 동일한 단어들은 출력하지 않습니다.
profile
자바, 웹 개발을 열심히 공부하고 있습니다!

0개의 댓글