Longest Common Substring

25 篇文章 0 订阅

有了前面Longest Common Subsequence的练习,这个题可以照葫芦画瓢,但是要注意的是,是什么的值可以传递,最后要返回的值是存在哪里的。

1. 这个是求子字符串,必须是连续的,即,如果i和j匹配,值只能从i-1,j-1处得到,再加一,如果不匹配,[i][j]即为0,不可传递。

2. 最大值是单独保存的,因为最大值无法在数组中持续传递

public class Solution {

    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    public int longestCommonSubstring(String A, String B) {
        // write your code here
        int al = A.length();
        int bl = B.length();
        int lcsCount = 0;
        int [][]lcs = new int[al+1][bl+1];
        for (int i = 1; i <= al; i++) {
            for (int j = 1; j <= bl; j++) {
                if (A.charAt(i-1)==B.charAt(j-1)) {
                    lcs[i][j] = lcs[i-1][j-1] + 1;
                    if (lcs[i][j] > lcsCount) {
                        lcsCount = lcs[i][j];
                    }
                }
            }
        }
        return lcsCount;
    }

}

下面是另一种做法

public int longestCommonSubstring(String A, String B) {

        // int la = A.length();
        // int lb = B.length();
        // int longestL = 0;
        // for(int i=0;i<la;i++){
        //     for(int j=0;j<lb;j++){
        //         int len = 0;
        //         while(i+len<la&&j+len<lb&&A.charAt(i+len)==B.charAt(j+len)){
        //             ++len;
        //             if(longestL<len)
        //                 longestL = len;
        //         }
        //     }
        // }
        // return longestL;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值