算法系列——最长公共子串

题目描述

给出两个字符串,找到最长公共子串,并返回其长度。

注意事项

子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

样例
给出A=“ABCD”,B=“CBCE”,返回 2

解题思路

应用动态规划,状态方程为 dp[i][j]表示
dp[i][j] 表示 A[i-1] B[j-1] 字符结尾的最长公共子串,
动态转移方程为:
如果A[i-1] == B[j-1], 则 dp[i][j] = dp[i-1][j-1]+1
否则 dp[i][j] = 0
最后求Longest Common Substring的长度等于

   max{  dp[i][j],  1<=i<=n, 1<=j<=m}

程序实现

public class Solution {
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
     // LCS 
    public int longestCommonSubstring(String A, String B) {
        if(A==null||A.length()==0||B==null||B.length()==0)
            return 0;
        char[] chA=A.toCharArray();
        char[] chB=B.toCharArray();
        int lenA=A.length();
        int lenB=B.length();
        int[][] dp=new int[lenA+1][lenB+1];
        int maxLen=0;
        //dp[i][j] 表示以 A[i-1] B[j-1] 结尾的公共子串长度  
        //覆盖可以覆盖所有所有字符
        for(int i=1;i<=lenA;i++)
            for(int j=1;j<=lenB;j++){
                if(chA[i-1]==chB[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=0;

                maxLen=Math.max(maxLen,dp[i][j]);
            }
        return maxLen;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章