Skip to content

Commit eee706d

Browse files
committed
#274 Longest Common Subsequence
1 parent 532e7b5 commit eee706d

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
# Time Complexity: O(m * n), where m = text1.length(), n = text2.length()
3+
# Space Complexity: O(m * n)
4+
5+
DP로 접근했습니다.
6+
text1[0..i], text2[0..j]의 LCS의 길이를 lcs[i][j]라고 정의하겠습니다. (0 <= i < m, 0 <= j < n)
7+
lcs[i - 1][j - 1], lcs[i - 1][j], lcs[i][j - 1]을 미리 구해두었다면, lcs[i][j]는 아래처럼 O(1)에 계산할 수 있습니다.
8+
9+
1. text1[i] != text2[j]인 경우
10+
lcs[i - 1][j] 를 기준으로 생각해보면, text1[i] != text2[j]이기 때문에, text1[0..i-1]에 text1[i]를 추가한다 해도, LCS의 길이에는 변화가 없습니다.
11+
마찬가지로 lcs[i][j - 1] 을 기준으로, text2[0..j-1]에 text2[j]를 추가해도, LCS의 길이에는 변화가 없습니다.
12+
따라서 lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]) 로 구할 수 있습니다.
13+
14+
2. text1[i] == text2[j]인 경우
15+
이 경우에는, lcs[i - 1][j - 1]에서 구한 LCS에 1글자가 추가되므로, lcs[i][j] = lcs[i - 1][j - 1] + 1 로 구할 수 있습니다.
16+
17+
3. i = 0 혹은 j = 0인 경우의 예외 로직을 추가하면, LCS의 길이를 구하는 2차원 DP를 구현할 수 있습니다.
18+
19+
*/
20+
21+
class Solution {
22+
public int longestCommonSubsequence(String text1, String text2) {
23+
int m = text1.length();
24+
int n = text2.length();
25+
int[][] lcs = new int[m][n];
26+
27+
for (int i = 0; i < m; i++) {
28+
for (int j = 0; j < n; j++) {
29+
if (text1.charAt(i) == text2.charAt(j)) {
30+
if (i == 0 || j == 0) {
31+
lcs[i][j] = 1;
32+
} else {
33+
lcs[i][j] = lcs[i - 1][j - 1] + 1;
34+
}
35+
} else {
36+
if (i == 0 && j == 0) {
37+
lcs[i][j] = 0;
38+
} else if (i == 0) {
39+
lcs[i][j] = lcs[i][j - 1];
40+
} else if (j == 0) {
41+
lcs[i][j] = lcs[i - 1][j];
42+
} else {
43+
lcs[i][j] = Math.max(lcs[i][j - 1], lcs[i - 1][j]);
44+
}
45+
}
46+
}
47+
}
48+
49+
return lcs[m - 1][n - 1];
50+
}
51+
}

0 commit comments

Comments
 (0)