Post

[백준] 17218번 - 비밀번호 만들기 [Java][C++]

[백준] 17218번 - 비밀번호 만들기 [Java][C++]

문제 링크


1. 문제 풀이

두 문자열의 가장 긴 부분 문자열을 구하는 문제로 LCS를 활용하면 된다. 이때 LCS의 길이가 아니라 실제 LCS를 출력해야 하는데 실제 LCS는 LCS를 구할 때 활용한 dp 테이블을 역추적하는 방식으로 구할 수 있다. 최종적으로 구하면 실제 LCS의 역순으로 조회되므로 이를 뒤집으면 실제 LCS를 구할 수 있다.


2. 코드

1. Bottom-Up dp [Java]

dp 테이블 앞에 패딩을 한 칸씩 줬다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.io.*;

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

        char[] str1 = br.readLine().toCharArray();
        char[] str2 = br.readLine().toCharArray();
        int N = str1.length;
        int M = str2.length;

        int[][] dp = new int[1 + N][1 + M];
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                if (str1[i - 1] == str2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        System.out.println(traceback(str1, str2, dp));
    }

    static String traceback(char[] str1, char[] str2, int[][] dp) {
        StringBuilder sb = new StringBuilder();

        int r = str1.length - 1;
        int c = str2.length - 1;

        while (r >= 0 && c >= 0) {
            if (str1[r] == str2[c]) {
                sb.append(str1[r]);
                r--;
                c--;
            } else {
                if (dp[r][c + 1] > dp[r + 1][c]) {
                    r--;
                } else {
                    c--;
                }
            }
        }

        return sb.reverse().toString();
    }
}

2. Bottom-Up dp [C++]

dp 테이블 앞에 패딩을 한 칸씩 줬다.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <bits/stdc++.h>
using namespace std;

string traceback(const string& s1, const string& s2, const vector<vector<int>>& dp) {
    string res;

    int r = s1.size() - 1;
    int c = s2.size() - 1;

    while (r >= 0 && c >= 0) {
        if (s1[r] == s2[c]) {
            res.push_back(s1[r]);
            r--;
            c--;
        } else {
            if (dp[r][c + 1] > dp[r + 1][c]) {
                r--;
            } else {
                c--;
            }
        }
    }

    reverse(res.begin(), res.end());
    return res;
}

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

    string s1, s2;
    cin >> s1 >> s2;

    int n = s1.size();
    int m = s2.size();

    vector<vector<int>> dp(1 + n, vector<int>(1 + m));
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s1[i - 1] == s2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    cout << traceback(s1, s2, dp);
}

3. 풀이 정보

1. Bottom-Up dp [Java]

언어시간메모리코드 길이
Java 11108 ms14176 KB1348 B

2. Bottom-Up dp [C++]

언어시간메모리코드 길이
C++ 170 ms2024 KB1074 B

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