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

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

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];

}

}

原文:http://www.cnblogs.com/qingjun/p/4805929.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值