构造m*n的矩阵,相等的那个位置等于1。此方法只能找到一个最长公共子序列,能得到长度
public static String LCS(String s1,String s2){//此方法只能找出一个LCS
int m = s1.length();
int n = s2.length();
int max = 0; //记录最长字串长度
int lastIndex = 0;//记录公共字串在S1的尾下标
int[][] b = new int[m][n];//构造一个m*n的矩阵,最长字串对应的斜线都为1,找出矩阵中最大的数
for(int i =0;i<m;i++){
for(int j = 0;j<n;j++){
if(s1.charAt(i) == s2.charAt(j)){
b[i][j] = 1;
if(i>0 && j>0){
b[i][j] = b[i-1][j-1]+1;
}
if(max < b[i][j]){
max = b[i][j];
lastIndex = i;
}
}else{
b[i][j] = 0;
}
}
}
//找出矩阵中最大的数后,根据最大数和lastIndex,找出最长公共字串
int startIndex = lastIndex-max+1;
String lcs = s1.substring(startIndex, lastIndex+1);
return lcs;
}