天天看點

leetcode 127 最長公共子串:給定兩個字元串str1和str2,輸出兩個字元串的最長公共子串 題目保證str1和str2的最長公共子串存在且唯一。 python

leetcode 127 最長公共子串 python

給定兩個字元串str1和str2,輸出兩個字元串的最長公共子串 題目保證str1和str2的最長公共子串存在且唯一。

class Solution:
    def LCS(self , str1 , str2 ):
        # write code here
        s1,s2='',''
        for i in str1:
            s1=s1+i
            if s1 in str2:
                if len(s1)>len(s2):
                    s2=s1
            else:
                s1=s1[1:]
        return s2