重复字符串查找

时间:2015-07-06 06:22:59

标签: python

我有一个像

这样的字符串模式
2 3 4 5 2 3 4 5 2 3 4 5 2 3 ...........

我需要找出重复的字符串2345

请注意,字符串的结尾(即最后一个字符)可以是2或3或4或5。

字符串也可以是

2 1 1 1 1 6 2 1 1 1 1 6 2 1 1 1 1 6 2 1 1 . . .

在这种情况下,我的答案是2 1 1 1 6。

任何简单快速的算法都可以实现这一目标吗?

我查看了几篇关于重复字符串的帖子并发现了这个正则表达式。但它并不适用于所有情况。

我正在寻找一些算法(而非重新)来解决这个问题。

import re
def findSeq(text):
    for i in range(1, len(text)/2 + 1):
        m = re.match(r'^(.{%d})\1+$'%i, text)
        if m:
            ret_num = len(m.group(1))
            return ret_num

3 个答案:

答案 0 :(得分:1)

我建议使用类似的算法:

def find_pattern(text):
    candidates = []
    for i, c in enumerate(text):
        candidates = [p_l for p_l in candidates if c == text[i%p_l]]
        for p_l in candidates:
            if not ((i+1) % p_l):
                break
        else:
            candidates.append(i+1)
    return text[:candidates[0]]

答案 1 :(得分:1)

我想这也会奏效。我还没有检查过所有边缘情况,但对于你描述的情况,它会起作用:

stream  = ['1' ,'1', '1', '1', '1', '6', '1', '1', '1', '1', '1', '6', '1', '1', '1', '1', '1', '6' ,'1', '1']
record = -1
same_items = -1
for k in xrange(2,len(stream)/2):
    s1 = stream[:k]
    s2 = stream[k: 2*k]
    if s1 == s2:
        #If all items are same, like 1,1,1,1,1,1,1
        if len(set(s2)) == 1:
            same_items = k
            continue
        else:
            record = k
            break

if record != -1:
    print stream[:k]
elif same_items!= -1:
    #This is when all the items in the stream are identical
    print stream[:k/2+1]

输出:

['1', '1', '1', '1', '1', '6']

时间复杂度 O(N ^ 2)

答案 2 :(得分:0)

序列总是从字符串的开头开始吗?如果是这样,这是一个很好的Pythonic解决方案:

def find_seq(s):
    for n in range(1, len(s)):
        if len({s[i:i+n] for i in range(0, len(s), n)}) == 1:
            return s[:n]

它的工作原理是将字符串分成相等长度的组以增加长度,直到找到答案。