python 最长公共子串长度

Given two strings, find the longest common substring.

Return the length of it.

Example

Given A = "ABCD", B = "CBCE", return 2.

Challenge

O(n x m) time and memory.

 

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 not (A and B):
            return 0

        M, N = len(A), len(B)

        f = [[0 for i in range(N + 1)] for j in range(M + 1)]
        for i in range(M):
            for j in range(N):
                if A[i] == B[j]:
                    f[i + 1][j + 1] = 1 + f[i][j]
        f = max(map(max, f))
        return f


猜你喜欢

转载自blog.csdn.net/zlsjsj/article/details/80214420