Dynamic programming problem-the longest common subsequence

Title description

Link: https://www.nowcoder.com/questionTerminal/c996bbb77dd447d681ec6907ccfb488a

Time limit: 3 seconds; space limit: 32768K

For two strings, please design an efficient algorithm to find the length of their longest common subsequence. The longest common subsequence here is defined as having two sequences U1, U2, U3...Un and V1, V2, V3...Vn, where Ui<Ui+1, Vi<Vi+1. And A[Ui] == B[Vi].

Given two strings A and B , given the lengths n and m of the two strings , please return the length of the longest common subsequence. Ensure that the length of the two strings is less than or equal to 300.

Test sample:

"1A2C3D4B56",10,"B1D23CA45B6A",12
返回:6

Problem-solving ideas

Define a matrix Z [m +. 1] [n-+. 1] , where Z [i] [j] represents a string A in the previous i strings and string B before j string of the longest common subsequence . Among them, z[0][j] row and z[i][0] represent the first row and first column of the matrix, and their values ​​are both 0. Next, when considering z[i][i] , first judge A Whether [i] and B[j] are the same, if they are the same, it is z[i-1][j-1]+1 , which is equivalent to adding 1 to the longest common string when one character is removed from both strings ; Otherwise, take the maximum value of z[i][j-1] and z[i-1][j] ; therefore, start from z[1][1] and calculate in the order from left to right and top to bottom The entire matrix z, the value at the lower right corner of the matrix z is the longest common subsequence of strings A and B.

The matrix z corresponding to the test example is:

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

Sample program:

# -*- coding:utf-8 -*-
class LCS:
    def findLCS(self, A, n, B, m):
        # write code here
        z = [[0 for i in range(n+1)] for j in range(m+1)]
        for i in range(1,m+1):
            for j in range(1,n+1):
                if A[j-1]==B[i-1]:
                    z[i][j] = z[i-1][j-1] + 1
                else:
                    z[i][j] = max(z[i-1][j],z[i][j-1])
        return z[m][n]

 

Guess you like

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