您的位置:首页 > 其它

Longest Common Substring

2016-05-26 15:17 232 查看
有了前面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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: