最长公共子串

找两个字符串的最长公共子串,这个子串要求在两个原字符串中是连续的。其实这又是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:”bab”和”caba”(当然我们现在一眼就可以看出来最长公共子串是”ba”或”ab”)
   b  a  b

c  0  0  0

a  0  1  0

b  1  0  2

a  0  2  0

package pack01;
//最长公共字串
public class test03 {
    public static void main(String[] args) {
        String str1="1234";
        String str2="413749120";
        int len = getLCString(str1.toCharArray(), str2.toCharArray());
        System.out.println(len);

    }
    public static int getLCString(char[] str1,char[] str2){
        int len1=str1.length;
        int len2=str2.length;
        int len=0;
        int [] c=new int[len2];
        for(int i=0;i<len1;i++){
            for(int j=len2-1;j>=0;j--){
                if(str1[i]==str2[j]){
                    if(i==0||j==0){
                        c[j]=1;
                    }else{
                        c[j]=c[j-1]+1;
                    }
                }else{
                    c[j]=0;
                }
                if(c[j]>len){
                    len=c[j];
                }
            }
        }
        return len;
    }
}

结果为2;
参考最长公共子串
参考最长公共子串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值