Lintcode(5)-最长公共子串

来源:互联网 发布:少女淘宝店铺推荐 编辑:程序博客网 时间:2024/05/22 12:06

Q:
给出两个字符串,找到最长公共子串,并返回其长度。
给出A=“ABCD”,B=“CBCE”,返回 2
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
A:
可以使用动态规划让时间复杂度降至O(n²)
关于动态规划这篇文章写得很好很强大!
这里使用最原始的办法,时间复杂度O(n³)

class Solution {public:    /**     * @param A, B: Two string.     * @return: the length of the longest common substring.     */    int longestCommonSubstring(string &A, string &B) {        std::size_t a_len = A.length();        std::size_t b_len = B.length();        if (!a_len || !b_len) {            return 0;        }        std::size_t a_start = std::string::npos;        std::size_t b_start = std::string::npos;        std::size_t longest = 0;        for (std::size_t i = 0; i < a_len; ++i) {            for (std::size_t j = 0; j < b_len; ++j) {                std::size_t this_l = 0;                std::size_t this_i = i;                std::size_t this_j = j;                for (; this_i < a_len && this_j < b_len; this_i++, this_j++) {                    if (A[this_i] == B[this_j])                        this_l++;                    else                        break;                }                if (this_l > longest) {                    longest = this_l;                    a_start = this_i;                    b_start = this_j;                }            }        }        return longest;    }};
0 0
原创粉丝点击