Skip to content

Commit f76f713

Browse files
committed
Solution: Longest Common Subsequence
1 parent 1c0c8a7 commit f76f713

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

longest-common-subsequence/flynn.cpp

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* 풀이 1
3+
* - 2차원 DP를 사용하여 풀이합니다
4+
* DP[i][j]: text1의 i번째 문자까지와 text2의 j번째 문자까지 비교했을 때, 가장 긴 공통 부분 문자열의 길이
5+
* 즉, text1[0 .. i - 1]와 text2[0 .. j - 1]의 가장 긴 공통 부분 문자열의 길이
6+
* DP[i][j] = if text1[i - 1] == text2[j - 1] then DP[i - 1][j - 1] + 1
7+
* else max(DP[i - 1][j], DP[i][j - 1])
8+
* - 풀이 2로 공간복잡도를 줄일 수 있습니다
9+
*
10+
* Big O
11+
* - M: text1의 길이
12+
* - N: text2의 길이
13+
*
14+
* - Time complexity: O(N * M)
15+
* - Space complexity: O(N * M)
16+
*/
17+
18+
class Solution {
19+
public:
20+
int longestCommonSubsequence(string text1, string text2) {
21+
size_t m = text1.size();
22+
size_t n = text2.size();
23+
24+
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
25+
26+
for (int i = 1; i <= m; ++i) {
27+
for (int j = 1; j <= n; ++j) {
28+
if (text1[i - 1] == text2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
29+
else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
30+
}
31+
}
32+
33+
return dp[m][n];
34+
}
35+
};
36+
37+
/**
38+
* 풀이 2
39+
* - 풀이 1의 DP 전개 과정을 보면 우리한테는 DP 배열 두 행만 필요하다는 걸 알 수 있습니다
40+
*
41+
* Big O
42+
* - M: text1의 길이
43+
* - N: text2의 길이
44+
*
45+
* - M >= N이 되도록 고릅니다
46+
*
47+
* - Time complexity: O(N * M)
48+
* - Space complexity: O(N)
49+
*/
50+
51+
class Solution {
52+
public:
53+
int longestCommonSubsequence(string text1, string text2) {
54+
size_t m = text1.size();
55+
size_t n = text2.size();
56+
57+
if (m < n) return longestCommonSubsequence(text2, text1);
58+
59+
vector<int> dp1(n + 1, 0);
60+
vector<int> dp2(n + 1, 0);
61+
62+
for (int i = 1; i <= m; ++i) {
63+
for (int j = 1; j <= n; ++j) {
64+
if (text1[i - 1] == text2[j - 1]) dp2[j] = dp1[j - 1] + 1;
65+
else dp2[j] = max(dp1[j], dp2[j - 1]);
66+
}
67+
68+
if (i == m) break;
69+
70+
dp1.swap(dp2);
71+
dp2.clear();
72+
dp2.resize(n + 1, 0);
73+
}
74+
75+
return dp2[n];
76+
}
77+
};

0 commit comments

Comments
 (0)