Pythonの最長共通部分列と最長共通部分列の問題(理解できません)

最近、Niuコースに最長共通部分列のdpバージョンを実装しましたが、acが使用できないことがわかりました。最長共通文字列と最長共通部分列を混同しているのではないかと思います。

最長共通部分列の実現は次のとおりです。

#
# 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]

ACが見つかりません

コードを最長の共通部分文字列に置き換える場合:

#
# 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

それはACであることが判明しました、そしてこれはまだ比較的暴力的な解決策です、私は本当に理由がわかりません

 

おすすめ

転載: blog.csdn.net/w5688414/article/details/113081137