leetcode 1143 - Longest Common Subsequence

https://leetcode.com/problems/longest-common-subsequence/

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
51
52
53
54
55
56
57
class Solution {
public:
/*
abcdexab
xcyeza

dp[i][j] =
1. max(dp[i-1][j], dp[i][j-1]), text1[i] != test2[j]
2. dp[i-1][j-1] + 1, text1[i] == test2[j]

dp[0][j] = 0
dp[i][0] = 0
*/
//2D array
int longestCommonSubsequence_2D_array(string text1, string text2) {
int len1 = text1.size(), len2 = text2.size();
int dp[len1+1][len2+1];

for (int i = 0; i <= len1; i++)
dp[i][0] = 0;
for (int j = 0; j <= len2; j++)
dp[0][j] = 0;

for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (text1[i-1] == text2[j-1])
dp[i][j] = dp[i-1][j-1] + 1;
else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}

return dp[len1][len2];
}

//1D array
int longestCommonSubsequence(string text1, string text2) {
int len1 = text1.size(), len2 = text2.size();
vector<int> dp(len2+1, 0);

for (int i = 1; i <= len1; i++) {
vector<int> tmp = dp;
for (int j = 1; j <= len2; j++) {
if (text1[i-1] == text2[j-1])
tmp[j] = dp[j-1] + 1;
else {
tmp[j] = max(dp[j], tmp[j-1]);
}
}

dp = tmp;
}

return dp[len2];
}
};