重复非重叠子串

2024-05-16 11:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这是查找最长的重复子字符串代码(源:geeksforgeks):

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的子串开始到以最长子串结束的较短的重复的非重叠子串?(尝试了各种更改,但始终没有得到正确的结果)。你知道吗


Tags: ofthetoinforindexifrange
1条回答
网友
1楼 · 发布于 2024-05-16 11:36:23

假设这是某种编程练习,我不想提供代码本身。我会提供提示。


How can it be modified to obtain also the shorter repeating non-overlapping substrings starting with the substrings of length x and ending with the longest substring? (tried various changes but never got the correct result).

请让我知道如果我理解你正确。。。你知道吗

你想得到所有不重叠的最长子串,对吗?你知道吗

第一个问题:不重叠意味着最长的子串可以切割其他长的子串。反之亦然。从最长到x搜索,而不是从x到最长。你知道吗

第二个问题:我们关心的是字符串的长度还是数量?你知道吗


如果我们只关心当前最长的时间,您可以:

  1. 找到最长的匹配
  2. 如果其长度超过所需长度x,请保存它(否则退出)
  3. 删除所有(?)?如果字符串有3个最长的重复,而不是2个呢?)出现字符串中最长的字符串;保留一些delimeter(因为例如abbcacbb有最长的子字符串bb-删除它将产生acac,得到ac,这是错误的)
  4. 重复

这基本上是伪代码,你需要“翻译”成真正的代码。使用while循环。;)

您不需要修改给定的函数—正如您所看到的,第1点是按原样使用它。您只需要从对该函数的多次调用中获得结果。;)

相关问题 更多 >