-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode1143.java
More file actions
36 lines (33 loc) · 1.21 KB
/
LeetCode1143.java
File metadata and controls
36 lines (33 loc) · 1.21 KB
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
public class LeetCode1143 {
public static void main(String[] args) {
// 输入:text1 = "abcde", text2 = "ace"
// 输出:3
System.out.println(new Solution1143().longestCommonSubsequence("abcde", "ace"));
// 输入:text1 = "abc", text2 = "abc"
// 输出:3
System.out.println(new Solution1143().longestCommonSubsequence("abc", "abc"));
// 输入:text1 = "abc", text2 = "def"
// 输出:0
System.out.println(new Solution1143().longestCommonSubsequence("abc", "def"));
}
}
class Solution1143 {
public int longestCommonSubsequence(String text1, String text2) {
// NOTE: 正向DP填表,利用缺省值为0
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
char c1 = text1.charAt(i - 1);
for (int j = 1; j <= n; j++) {
char c2 = text2.charAt(j - 1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}