LintCode Longest Common Substring

Given two strings, find the longest common substring.
Return the length of it.
Have you met this question in a real interview? Yes
Example
Given A = "ABCD", B = "CBCE", return 2.
Note
The characters in substring should occur continuously in original string. This is different with subsequence.
Challenge
O(n x m) time and memory.

LintCode 也是个不错的平台,尤其现在leetcode访问有些问题。

常规dp:

class Solution {
public:    
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    int longestCommonSubstring(string &A, string &B) {
        // write your code here
        int alen = A.size();
        int blen = B.size();
        vector<int> dp0(blen + 1);
        vector<int> dp1(blen + 1);
        
        int longest = 0;
        for (int i = 1; i <= alen; i++) {
            for (int j = 1; j <= blen; j++) {
                dp1[j] = A[i - 1] != B[j - 1] ? 0 : 1 + dp0[j-1];
                longest = max(longest, dp1[j]);
            }
            swap(dp0, dp1);
        }
        return longest;
    }
};

posted @ 2015-09-11 23:14  卖程序的小歪  阅读(113)  评论(0编辑  收藏  举报