-
Notifications
You must be signed in to change notification settings - Fork 0
/
1143. Longest Common Subsequence
65 lines (47 loc) · 1.34 KB
/
1143. 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
58
59
60
61
62
63
64
65
class Solution {
public int longestCommonSubsequence(String text1, String text2)
{
char[] s1 = text1.toCharArray();
char[] s2 = text2.toCharArray();
int len1 = s1.length;
int len2 = s2.length;
int[] dp = new int[len2 + 1];
for (int i = 0; i < len1; i++)
{
int prev = dp[0];
for (int j = 1, len = dp.length; j < len; j++)
{
int temp = dp[j];
if (s1[i] == s2[j - 1])
{
dp[j] = prev + 1;
}
else
{
dp[j] = Math.max(dp[j - 1], dp[j]);
}
prev = temp;
}
}
return dp[len2];
/*
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
{
if (text1.charAt(i - 1) == text2.charAt(j - 1))
{
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else
{
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
*/
}
}