题目
思路及代码
import java.util.*;
public class Solution {
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
public static String LCS(String s1, String s2) {
char[] cs1 = s1.toCharArray();
char[] cs2 = s2.toCharArray();
int[][] dp = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i < dp.length; i++) {
dp[i][0] = 0;
}
for (int j = 0; j < dp[0].length; j++) {
dp[0][j] = 0;
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (cs1[i - 1] == cs2[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]);
}
}
}
int len = dp[s1.length()][s2.length()];
char[] lcs = new char[len];
createLCS(cs1, cs2, dp, s1.length(), s2.length(), lcs, len);
String reslit = new String(lcs);
if(reslit.length() == 0) return"-1";
//注意字符串不为空也有可能没有公共子序列
else
return reslit;
}
public static void createLCS(char[] cs1, char[] cs2, int[][] dp, int x, int y, char[] lcs, int len) {
if (x < 1 || y < 1 || len < 0) {
return;
}
if (cs1[x - 1] == cs2[y - 1]) {
lcs[--len] = cs1[x - 1];
// 如果相等来源于左上角元素
createLCS(cs1, cs2, dp, x - 1, y - 1, lcs, len);
//return;
} else {
if (dp[x][y] == dp[x][y - 1]) {// 不相等来源于左边
createLCS(cs1, cs2, dp, x, y - 1, lcs, len);
return;
//return 是给第一个相同字符用于结束递归的,假如不是第一个,
//递归总能找到一个左上角相等的字符,因此不需要结束递归
}
if (dp[x][y] == dp[x - 1][y]) {// 不相等来源于上边
createLCS(cs1, cs2, dp, x - 1, y, lcs, len);
return;
}
}
}
}
import java.util.*;
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";
int l1= s1.length();
int l2= s2.length();
int [][] c = new int [l1][l2];
//存储记录表
for(int i = 1;i< l1;i++){
for(int j = 1;j<l2;j++){
if(i == 0|| j==0) c[i][j] = 0;
else if(s1.charAt(i-1)== s2.charAt(j-1)) c[i][j]= c[i-1][j-1]+1;
else c[i][j]= Math.max(c[i-1][j],c[i][j-1]);
}
}
//递归开始调用
int len = c[l1-1][l2-1];
char [] s = new char [len];
lcs(s1,s2,c,s,l1,l2,len);
return new String(s);
// return(lcs(s1,s2,c,s,l1-1,l2-1,len));
}
public void lcs( String s1, String s2,int [][] c, char [] s,int len1,int len2,int len){
if(len1< 1|| len2 < 1 || len < 0) return ;
if(s1.charAt(len1-1)== s2.charAt(len2-1)){
// s[len--]= s1.charAt(len1);
s[--len]= s1.charAt(len1);
lcs(s1,s2,c,s,len1-1,len2-1,len-1);
return;
}else{
if(c[len1][len2]== c[len1-1][len2]){
lcs(s1,s2,c,s,len1-1,len2,len);
return;
}
if(c[len1][len2]== c[len1][len2-1]){
lcs(s1,s2,c,s,len1,len2-1,len);
return;
}
}
//return (new String(s));
}
}