[백준] 1181번: 단어 정렬 자바

이다혜·2024년 2월 6일
0

백준

목록 보기
17/29

📎 문제 출처


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

📌 문제 설명


❓ 풀이 방법1


Arrays.sort를 사용하여 String 배열을 Comparator를 통해 정렬한다.
Comparator의 compare 메서드를 재정의하여, 먼저 문자열의 길이를 기준으로 비교하고, 길이가 같으면 사전순으로 정렬한다.

문자열을 사전순으로 정렬할 때는 compareTo() 메서드를 사용한다.
compareTo() 메소드는 호출하는 객체와 파라미터로 전달받은 객체를 비교하여, 다음 세 가지 중 하나의 값을 반환한다.

음수: 호출하는 객체가 파라미터로 전달받은 객체보다 작다
0: 두 객체가 같다.
양수: 호출하는 객체가 파라미터로 전달받은 객체보다 크다

📌 Code1


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

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

        String[] words = new String[n];
        for (int i = 0; i < n; i++) {
            words[i] = br.readLine();
        }

        Arrays.sort(words, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if(o1.length() == o2.length()) {
                    return o1.compareTo(o2);
                }
                return o1.length() - o2.length();
            }
        });

        StringBuilder sb = new StringBuilder();
        sb.append(words[0] + "\n");
        for(int i = 1; i < n; i++) {
            if(!words[i].equals(words[i-1])) {
                sb.append(words[i] + "\n");
            }
        }

        System.out.println(sb.toString());
    }
}

❓ 풀이 방법2


두 번째 방법은 위의 코드를 람다식으로 작성해보았다.

📌 Code2


package com.ll;

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

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

        String[] words = new String[n];
        for (int i = 0; i < n; i++) {
            words[i] = br.readLine();
        }

        Arrays.sort(words, (w1, w2) -> {
            if(w1.length() == w2.length()) {
                return w1.compareTo(w2);
            }
            return w1.length() - w2.length();
        });

        StringBuilder sb = new StringBuilder();
        sb.append(words[0] + "\n");
        for(int i = 1; i < n; i++) {
            if(!words[i].equals(words[i-1])) {
                sb.append(words[i] + "\n");
            }
        }

        System.out.println(sb.toString());
    }
}

풀이 결과 람다식을 사용했을 때 시간이 조금 단축되었다.

0개의 댓글