Longest Common Substring

Longest Common Substring

Given two strings, find the longest common substring.

Return the length of it.

Example

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

Solution

class Solution:
    # @param A, B: Two string.
    # @return: the length of the longest common substring.
    def longestCommonSubstring(self, A, B):

        if len(A) ==0 or len(B) == 0:
            return 0
        m = len(A)
        n = len(B)
        f = [[0 for x in range(n + 1)] for y in range(m + 1)]
        f[0][0] = 0 
        result = 0 
        for i in range(1, m + 1):
            for j in range(1,n + 1):
                if A[i - 1 ] == B[j - 1]:
                    f[i][j] = f[i - 1][j - 1] + 1
                    result = max(result,f[i][j])
        return result

Last updated

Was this helpful?