The problem of the longest common subsequence and the longest common substring in python (do not understand)

Recently, I implemented the dp version of the longest common subsequence on Niu course. I found that ac cannot be used. I suspect that they confuse the longest common string with the longest common subsequence.

The realization of the longest common subsequence is:

#
# longest common subsequence
# @param s1 string字符串 the string
# @param s2 string字符串 the string
# @return string字符串
#
class Solution:
    def LCS(self , s1 , s2 ):
        # write code here
        m=len(s1)
        n=len(s2)
        dp=[[0]*(n+1) for i in range(m+1)]
        for i in range(m+1):
            for j in range(n+1):
                if(i==0 or j==0):
                    continue
                elif(s1[i-1]==s2[j-1]):
                    dp[i][j]=dp[i-1][j-1]+1
                else:
                    dp[i][j]=max(dp[i][j-1],dp[i-1][j])
        i=m
        j=n
        lcs=''
        while(i>0 and j>0):
            if(s1[i-1]==s2[j-1]):
                lcs+=s1[i-1]
                i-=1
                j-=1
            elif(dp[i][j-1]>=dp[i-1][j]):
                j-=1
            elif(dp[i][j-1]<dp[i-1][j]):
                i-=1
            else:
                break
        return lcs[::-1]

Found no ac

When replacing the code with the longest common substring:

#
# longest common subsequence
# @param s1 string字符串 the string
# @param s2 string字符串 the string
# @return string字符串
#
class Solution:
    def LCS(self , s1 , s2 ):
        # write code here
        max_len=0
        res=''
        if(len(s1)>len(s2)):
            s1,s2=s2,s1
        for i in range(len(s1)):
            if(s1[i-max_len:i+1] in s2):
                res=s1[i-max_len:i+1]
                max_len+=1
        if(res==''):
            return -1
        else:
            return res

It turned out to be ac, and this is still a relatively violent solution, I really don’t know why

 

Guess you like

Origin blog.csdn.net/w5688414/article/details/113081137