LintCode Longest Common Substring

最长公共子串算法
本文介绍了一种寻找两个字符串中最长公共子串的算法,并提供了一个具体的实现案例。该算法采用动态规划方法,在O(nxm)的时间复杂度内解决问题。

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;
    }
};

转载于:https://www.cnblogs.com/lailailai/p/4802322.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值