给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。
两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。
输入:text1 = "abcde", text2 = "ace" 输出:3 解释:最长公共子序列是 "ace" ,它的长度为 3 。
public class Solution {
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
public String LCS (String s1, String s2) {
// write code here
if (s1.length() == 0 || s2.length() == 0) {
return "-1";
}
char[] c1 = s1.toCharArray(), c2 = s2.toCharArray();
int[][] dp = new int[c1.length+1][c2.length+1];
for (int i = 1; i <= c1.length; i++) {
for (int j = 1; j <= c2.length; j++) {
if (c1[i-1] == c2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
}else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
if (dp[c1.length][c2.length] == 0) {
return "-1";
}
StringBuilder ans = new StringBuilder();
int len = dp[c1.length][c2.length], x = c1.length, y = c2.length;
while (len > 0) {
if (c1[x-1] == c2[y-1] && dp[x][y] == dp[x-1][y-1] + 1) {
ans.append(c1[x-1]);
x--;
y--;
len--;
}else if (dp[x-1][y] == dp[x][y]) {
x--;
}else {
y--;
}
}
return ans.reverse().toString();
}
}