python - 搜索长的连续重复子串

标签 python algorithm substring

我有一串 0 和 1。将“contiguous-double”定义为立即重复的子字符串。例如,字符串“011101010101110”可以分解为“011 1010 1010 1110”,可以压缩为“011(1010)1110”。

是否有一种好的算法可以在一个字符串中找到所有连续的 double ?我能想到的最好的是关于字符串长度的二次方:

def all_contiguous_doubles(s):
    for j in range(len(s)):
        for i in range(j):
            if s[i:j] == s[j:2*j - i]:
                print "%s(%s)%s" % (s[:i], s[i:j], s[2*j - i:])

最佳答案

在这里,我展示了我的动态规划解决方案,其时间复杂度为 O(n^2) 并且 O(n^2) 的空间复杂度,其中 n 是原始字符串的长度。

下面我递归定义了函数dl(r,c)。 如果您将 dl(r,c) 设为表格并按正确顺序填写,您将在 O(n^2) 内完成它。

定义:

char(i) = character at position i

substr(i) = substring starting from position i towards the end of original string.

dl(r,c) = length of common, non-overlapping prefix of substr(r) and substr(c).

dl(r,c) 的递归定义:

Since dl(r,c) is symmetric, we will only consider r <= c.

dl(r,c) = 0 when r == c. Because if the substring starts at the same point, it will always be overlapping.

dl(r,c) = 0 when char(r) != char(c). Because the prefix is not the same.

if char(r) == char(c),
    if dl(r+1,c+1) + 1 < c-r
        dl(r,c) = dl(r+1,c+1) + 1
    else
        dl(r,c) = dl(r+1,c+1)

dl(r,c)dl(r,c) == c-r 的最大值就是你的答案。

关于python - 搜索长的连续重复子串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13464539/

相关文章:

Python列表问题

python - 如何在 Google App Engine 上防止 "ImportError: No module named oauth2client.client"?

python - 我如何在 Python 中传送 turtle ?

php - 我的网站在庞大的数据库中搜索数据。我应该使用 Lucene 来搜索还是自己编写算法?

algorithm - 算法中 "fractional"的定义

Python - 解析具有可变重复子字符串的字符串

javascript - 子字符串似乎不起作用

Python:Scapy:如何读取 IP 标志

javascript - 如何在javascript中子串

algorithm - 检测不规则形状运动物体碰撞的数据结构和算法