Skip to content

Commit eee706d

Browse files
committed
DaleStudy#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)