【发布时间】:2019-10-07 11:55:25
【问题描述】:
这是寻找最长的重复子串代码(来源:geeksforgeeks):
def longestRepeatedSubstring(str):
n = len(str)
LCSRe = [[0 for x in range(n + 1)]
for y in range(n + 1)]
res = "" # To store result
res_length = 0 # To store length of result
# building table in bottom-up manner
index = 0
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
# (j-i) > LCSRe[i-1][j-1] to remove
# overlapping
if (str[i - 1] == str[j - 1] and
LCSRe[i - 1][j - 1] < (j - i)):
LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1
# updating maximum length of the
# substring and updating the finishing
# index of the suffix
if (LCSRe[i][j] > res_length):
res_length = LCSRe[i][j]
index = max(i, index)
else:
LCSRe[i][j] = 0
# If we have non-empty result, then insert
# all characters from first character to
# last character of string
if (res_length > 0):
for i in range(index - res_length + 1,
index + 1):
res = res + str[i - 1]
return res
# Driver Code
if __name__ == "__main__":
str = "geeksforgeeks"
print(longestRepeatedSubstring(str))
# This code is contributed by ita_c
如何修改它以获得较短的重复非重叠子串,以长度为 x 的子串开始并以最长的子串结束? (尝试了各种更改,但从未得到正确的结果)。
【问题讨论】:
-
您能否提供输入和预期输出的示例?它将帮助用户回答
-
How can it be modified to obtain also the shorter最短的总是长度为 1 或 0(空字符串理论上是子字符串)。你对“更短”的理解是什么?你想要第二长的吗?或者任何字符串?或者如果有两个相同(最长)的长度,让它们都得到而不是最长的? -
应找到所有长度为 x 和更长(最长)的重复子字符串。重复次数无关紧要。不能有任何重叠,也不能有较长子串的子串。 IE。结果表中的所有子字符串都不与任何其他子字符串共享任何元素。示例:x=3,字符串:47358917948809837074317946984339473589669843698370880,结果:880//1794//69843//98370//473589