题目
给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。
若这两个字符串没有公共子序列,则返回 0。
代码
二维数组
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
char c1 = text1.charAt(i), c2 = text2.charAt(j);
dp[i + 1][j + 1] = c1 == c2 ? dp[i][j] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
}
}
return dp[m][n];
}
} 一维数组
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int m = text1.length(), n = text2.length();
int[] dp = new int[n + 1];
int tmp;
for (int i = 0; i < m; i++) {
int last = 0; // 左上角 dp[i][j]
for (int j = 0; j < n; j++) { // 当前坐标为 i+1,j+1
tmp = dp[j + 1]; // 正上方 dp[i+1][j]
char c1 = text1.charAt(i), c2 = text2.charAt(j);
dp[j + 1] = c1 == c2 ? last + 1 : Math.max(tmp, dp[j]);
last = tmp;
}
}
return dp[n];
}
} 
京公网安备 11010502036488号