Leetcode 1044.最长重复子串 python实现

题目描述(点我看原题)

给出一个字符串 S,考虑其所有重复子串(S 的连续子串,出现两次或多次,可能会有重叠)。
返回任何具有最长可能长度的重复子串。(如果 S 不含重复子串,那么答案为 “”。)

示例 1:
输入:“banana”
输出:“ana”

示例 2:
输入:“abcd”
输出:""

思路: 遍历字符串s,如果字母x出现在s中多次,就查看这几个位置后面的字母是否还相同(这几个位置:字母x出现的当前位置 及之后出现的位置。),记录x的位置以及后续有几个字母相同,取后续字母相同数量最多的为最终结果。

目前实现的不够简便

class Solution(object):
    def longestDupSubstring(self, s):
        lis,i = [],0
        while True:
            if i < len(s)-1:
                a = {m for m,j in enumerate(s) if j==s[i] and m>= i}
                h = 0
                k = i + 1
                while True:
                    b = {m+1 for m in a if m<len(s)-1 and s[m+1]==s[min(a)+1]}
                    if len(b) > 1:
                        a = b
                        h += 1
                        k += 1
                    else:
                        if h != 0:
                            lis.append([h,min(a)])
                        i = k
                        break
                if k == len(s)-1 and h != 0:
                    lis.append([h,min(b)])
                    break
            else:
                break
        if lis != []:
            a = [i[0] for i in lis]
            xb = lis[a.index(max(a))]
            return s[xb[1]-xb[0]:xb[1]+1]
        else:
            return ''
发布了14 篇原创文章 · 获赞 8 · 访问量 669

猜你喜欢

转载自blog.csdn.net/weixin_44133727/article/details/100016727