Post

[백준] 1181번 - 단어 정렬 [Java][C++]

[백준] 1181번 - 단어 정렬 [Java][C++]

문제 링크


1. 문제 풀이

길이가 짧은 것부터, 길이가 같으면 사전 순으로 정렬해서 출력하는 문제로 중복된 단어는 하나만 남기고 제거해야 한다. 조건에 맞춰 정렬을 먼저하고 출력 과정에서 이전 단어와 현재 단어가 동일하면 출력하지 않고 넘어가고 다르면 출력하고 이전 단어를 현재 단어로 갱신해주면 된다. 집합을 활용해서 먼저 중복을 제거해도 된다.


2. 코드

1. 정렬 [Java]

compareTo 메서드가 사전 순 정렬인 점을 활용해서 람다식을 구성했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int N = Integer.parseInt(br.readLine());

        String[] arr = new String[N];
        for (int i = 0; i < N; i++) {
            arr[i] = br.readLine();
        }
        Arrays.sort(arr, (o1, o2) -> {
            if (o1.length() != o2.length()) return Integer.compare(o1.length(), o2.length());
            return o1.compareTo(o2);
        });

        String prev = "";
        for (String str : arr) {
            if (str.equals(prev)) continue;

            bw.write(str);
            bw.newLine();
            prev = str;
        }

        bw.flush();
    }
}

2. 정렬 [C++]

a < b 가 사전 순 정렬인 점을 활용해서 람다식을 구성했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<string> v(n);
    for (string& x : v) cin >> x;
    sort(v.begin(), v.end(), [](const string& a, const string& b) {
        if (a.size() != b.size()) return a.size() < b.size();
        return a < b;
    });

    string prev = "";
    for (string& s : v) {
        if (s == prev) continue;

        cout << s << '\n';
        prev = s;
    }
}

3. 풀이 정보

1. 정렬 [Java]

언어시간메모리코드 길이
Java 11304 ms22524 KB865 B

2. 정렬 [C++]

언어시간메모리코드 길이
C++ 1716 ms3976 KB497 B

This post is licensed under CC BY 4.0 by the author.