Dynamic programming problem-the longest common substring

Title description

Link: https://www.nowcoder.com/questionTerminal/02e7cc263f8a49e8b1e1dc9c116f7602

Time limit: 3 seconds; space limit: 32768K

For two strings, please design an algorithm with a time complexity of O(m*n) (where m and n are the lengths of the two strings) to find the length of the longest common substring of the two strings. The longest common substring here is defined as two sequences U1, U2,...Un and V1,V2,...Vn, where Ui + 1 == Ui+1, Vi + 1 == Vi+1, and Ui == Vi.

Given two strings A and B , the lengths of the two strings n and m are given at the same time .

Test sample:

"1AB2345CD",9,"12345EF",7 
returns: 4

Problem-solving ideas

The difference between the longest common substring and the longest common subsequence is that the substrings must be continuous. A matrix z of size n*m can be constructed . The corresponding position z[i][j] on the matrix represents whether A[i] and B[j] are the same. Only the numbers on a continuous diagonal line are the same, which represents the position It is a common string of two strings AB. Thus, for z [i] [j], when A [i] and B [j] is not equal to the values 0 ; if equal then take z [i-1] [j -1] value of plus 1 for Represents the length of the current public string. Finally, the maximum value of the entire matrix z is output, which is the length of the longest common substring.

The matrix z corresponding to the test example is:

[[1, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 2, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 3, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 4, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0]]

Sample program:

# -*- coding:utf-8 -*-
class LongestSubstring:
    def findLongest(self, A, n, B, m):
        # write code here
        z = [[0 for i in range(m)] for j in range(n)]
        max_val = 0 #记录最大值
        for i in range(n):
            for j in range(m):
                if A[i]==B[j]:
                    if i==0 or j==0:
                        z[i][j] = 1
                    else:
                        z[i][j] = z[i-1][j-1]+1
                    if z[i][j]>max_val:
                        max_val = z[i][j]
        return max_val

 

Guess you like

Origin blog.csdn.net/qq_14997473/article/details/89381860