-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
58 lines (54 loc) · 1.88 KB
/
Solution.java
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
package L1143;
public class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
text1 = " " + text1;
text2 = " " + text2;
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i) == text2.charAt(j)) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
return f[m][n];
}
public int longestCommonSubsequence2(String text1, String text2) {
int m = text1.length(), n = text2.length();
text1 = " " + text1;
text2 = " " + text2;
int[][] f = new int[m + 1][n + 1];
int[][] preType = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i) == text2.charAt(j)) {
f[i][j] = f[i - 1][j - 1] + 1;
preType[i][j] = 2;
} else {
if (f[i - 1][j] > f[i][j - 1]) {
f[i][j] = f[i - 1][j];
preType[i][j] = 0;
} else {
f[i][j] = f[i][j - 1];
preType[i][j] = 1;
}
}
}
}
print(text1, text2, preType, m, n);
return f[m][n];
}
void print(String text1, String text2, int[][] preType, int i, int j) {
if (i == 0 || j == 0)
return;
if (preType[i][j] == 0)
print(text1, text2, preType, i - 1, j);
else if (preType[i][j] == 1)
print(text1, text2, preType, i, j - 1);
else
print(text1, text2, preType, i - 1, j - 1);
}
}