最长公共字串---动态规划

来源:互联网 发布:张继科mac口红什么梗 编辑:程序博客网 时间:2024/06/01 08:15

对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度。这里的最长公共子串的定义为两个序列U1,U2,..Un和V1,V2,...Vn,其中Ui + 1 == Ui+1,Vi + 1 == Vi+1,同时Ui == Vi。

给定两个字符串AB,同时给定两串的长度nm

测试样例:
"1AB2345CD",9,"12345EF",7
返回:4


代码如下:

class LongestSubstring {
public:
    int findLongest(string A, int n, string B, int m) {
        // write code here
        int dp[n][m];
        for(int i=0;i<n;++i){
            if(B[0]==A[i])
                dp[i][0]=1;
            else
                dp[i][0]=0;
        }
        for(int j=0;j<m;++j){
            if(A[0]==B[j])
                dp[0][j]=1;
            else
                dp[0][j]=0;
        }
        for(int i=1;i<n;++i){
            for(int j=1;j<m;++j){
                if(A[i]==B[j])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=0;
            }
        }
        int max=0;
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                if(dp[i][j]>max)
                    max=dp[i][j];
            }
        }
        return max;
    }
};


0 0