最长公共子字符串(动态规划)

来源:互联网 发布:mac新建文件夹 编辑:程序博客网 时间:2024/05/21 17:32

和经典DP最长公共子串(不要求字符连续)不同,最长公共子字符串要求字符是连续的

class LongestSubstring {public:    int findLongest(string A, int n, string B, int m) {        //f[i][j] represent the longest common substring starting with A[i] and B[j]        vector<vector<int>> f(n+1, vector<int>(m+1, 0));        //maxlen is the overall max common substring length, starting anywhere        int maxlen = 0;        //dp        for(int i = n-1; i > -1; --i){            for(int j = m-1; j > -1; --j){                if(A[i] != B[j]){                    //no such common substring ended with A[i] and B[j]                    //f[i][j] remain 0 as initialized                }                else{                    //common substring starts with A[i] and B[j]                    f[i][j] = f[i+1][j+1] + 1;                    maxlen = max(maxlen, f[i][j]);                }            }        }        return maxlen;    }};


0 0
原创粉丝点击