美文网首页
lintcode 79. 最长公共子串

lintcode 79. 最长公共子串

作者: cuizixin | 来源:发表于2018-08-27 17:53 被阅读3次

    难度:中等

    1. Description

    79. 最长公共子串

    2. Solution

    动态规划入门题


    思路
    • python3
    class Solution:
        """
        @param A: A string
        @param B: A string
        @return: the length of the longest common substring.
        """
        def longestCommonSubstring(self, A, B):
            # write your code here
            if A=='' or B=='':
                return 0
            dp = [[0 for j in range(len(B))] for i in range(len(A))]
            
            res = 0
            for i in range(len(A)):
                if A[i]==B[0]:
                    dp[i][0]=1
                    res=1
            for i in range(len(B)):
                if B[i]==A[0]:
                    dp[0][i]=1
                    res=1
            
            for i in range(1,len(A)):
                for j in range(1,len(B)):
                    if A[i]==B[j]:
                        dp[i][j] = dp[i-1][j-1]+1
                        res = max(res, dp[i][j])
            return res
    

    3. Reference

    1. https://www.lintcode.com/problem/longest-common-substring/description

    相关文章

      网友评论

          本文标题:lintcode 79. 最长公共子串

          本文链接:https://www.haomeiwen.com/subject/caytwftx.html