动态规划之----求两个字符串的最长公共子序列

package DongtaiGuihua;

/**
* Created by hunk on 2015/9/13.
*/
public class LongestCommonSubstring {

public static void main(String[] args){
String str1="BDCABA";
String str2="ABCBDAB";
System.out.println(findMaxCommonSubstring(str1,str2,str1.length()-1,str2.length()-1));
System.out.println(findMaxCommonSubstring2(str1,str2));
}

public static int findMaxCommonSubstring(String str1,String str2,int i,int j){//获取最大非连续公共子串长度,递归
if(i==-1 ||j==-1){
return 0;
}
if (str1.charAt(i)==str2.charAt(j)){
return findMaxCommonSubstring(str1,str2,i-1,j-1)+1;
}else {
return Math.max(findMaxCommonSubstring(str1,str2,i,j-1),findMaxCommonSubstring(str1,str2,i-1,j));
}
}

public static int findMaxCommonSubstring2(String str1,String str2){//非递归
int str1Len=str1.length();
int str2Len=str2.length();
int[][] len= new int[str1Len+1][str2Len+1];
for(int i=0;i<=str2Len;i++){
len[0][i]=0;
}
for(int j=0;j<str1Len;j++){
len[j][0]=0;
}
for(int i=1;i<=str1.length();i++){//状态迁移方程
for(int j=1;j<=str2.length();j++){
if (str1.charAt(i-1)==str2.charAt(j-1)){
len[i][j]=len[i-1][j-1]+1;
}else if (len[i-1][j]>=len[i][j-1]){
len[i][j]=len[i-1][j];
}else {
len[i][j]=len[i][j-1];
}
}
}

for(int i=0;i<=str1Len;i++){//打印状态矩阵
for(int j=0;j<=str2Len;j++){
System.out.print(len[i][j]+" ");
}
System.out.println();
}
int i=1,j=1;
while (i<=str1Len&&j<=str2Len){//输出序列
if(str1.charAt(i-1)==str2.charAt(j-1)){
System.out.print(str1.charAt(i-1));
i++;
j++;
}else if (j+1>str2Len&&i+1<=str1Len){
i++;
}else if (i+1>str1Len&&j+1<=str2Len){
j++;
}else if(len[i+1][j]>len[i][j+1]){
i++;
}else {
j++;
}
}
System.out.println();
return len[str1Len][str2Len];
}
}
原文地址:https://www.cnblogs.com/qingjun/p/4805929.html