首页 > 其他 > 详细

79 最长公共子串

时间:2018-07-13 21:56:22      阅读:219      评论:0      收藏:0      [点我收藏+]

原题网址:https://www.lintcode.com/problem/longest-common-substring/description

描述

给出两个字符串,找到最长公共子串,并返回其长度。

 

子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

您在真实的面试中是否遇到过这个题?  

样例

给出A=“ABCD”,B=“CBCE”,返回 2

挑战

O(n x m) time and memory.

标签
字符串处理
LintCode 版权所有
 
思路:依旧是动态规划。
 
AC代码
class Solution {
public:
    /**
     * @param A: A string
     * @param B: A string
     * @return: the length of the longest common substring.
     */
    int longestCommonSubstring(string &A, string &B) {
        // write your code here
    int n1=A.size(),n2=B.size();
     if (n1==0||n2==0)
     {
         return 0;
     }
     vector<vector<int>> dp(n1+1,vector<int>(n2+1,0));
    int maxl=-1;
     for (int i=1;i<=n1;i++)
     {
         for (int j=1;j<=n2;j++)
         {
            if (A[i-1]==B[j-1])
            {
                dp[i][j]=dp[i-1][j-1]+1;
            }
            maxl=max(maxl,dp[i][j]);
         }
     }

     return maxl;
    }
};

 

 
 
 

79 最长公共子串

原文:https://www.cnblogs.com/Tang-tangt/p/9307477.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!