在文件中查找最常见的子字符串模式

时间:2014-08-01 02:02:56

标签: python string algorithm data-structures substring

您将获得一个字符串:

input_string = """
HIYourName=this is not true
HIYourName=Have a good day
HIYourName=nope
HIYourName=Bye!"""

找到文件中最常见的子字符串。 答案是“HiYourName =”。 注意,具有挑战性的部分是HiYourName =在字符串中不是“单词”本身 即它不是由它周围隔开而界定的。

所以,只是为了澄清,这不是最常见的单词问题。

4 个答案:

答案 0 :(得分:3)

这是一个简单的蛮力解决方案:

from collections import Counter

s = " HIYourName=this is not true HIYourName=Have a good day HIYourName=nope HIYourName=Bye!"
for n in range(1, len(s)):
    substr_counter = Counter(s[i: i+n] for i in range(len(s) - n))
    phrase, count = substr_counter.most_common(1)[0]
    if count == 1:      # early out for trivial cases
        break
    print 'Size: %3d:  Occurrences: %3d  Phrase: %r' % (n, count, phrase)

示例字符串的输出为:

Size:   1:  Occurrences:  10  Phrase: ' '
Size:   2:  Occurrences:   4  Phrase: 'Na'
Size:   3:  Occurrences:   4  Phrase: 'Nam'
Size:   4:  Occurrences:   4  Phrase: 'ourN'
Size:   5:  Occurrences:   4  Phrase: 'HIYou'
Size:   6:  Occurrences:   4  Phrase: 'IYourN'
Size:   7:  Occurrences:   4  Phrase: 'urName='
Size:   8:  Occurrences:   4  Phrase: ' HIYourN'
Size:   9:  Occurrences:   4  Phrase: 'HIYourNam'
Size:  10:  Occurrences:   4  Phrase: ' HIYourNam'
Size:  11:  Occurrences:   4  Phrase: ' HIYourName'
Size:  12:  Occurrences:   4  Phrase: ' HIYourName='
Size:  13:  Occurrences:   2  Phrase: 'e HIYourName='

答案 1 :(得分:1)

您可以在线性时间内在字符串中构建后缀树或后缀数组(请参阅http://en.wikipedia.org/wiki/Suffix_tree及其中的链接),然后在构建后缀树之后,您还可以通过深度优先搜索线性time计算线性时间内所有最长的子串的后缀前缀数(子串的出现次数),并将此信息存储在后缀树中的每个节点上。然后,您只需要搜索树以查找子串的最大出现次数(线性时间),然后返回最长次出现的子串(也是线性时间)。

答案 2 :(得分:1)

另一个没有进口的蛮力:

s = """ HIYourName=this is not true HIYourName=Have a good day HIYourName=nope HIYourName=Bye!"""

def conseq_sequences(li):
    seq = []
    maxi = max(s.split(),key=len) # max possible string cannot span across spaces in the string
    for i in range(2, len(maxi)+ 1): # get all substrings from 2 to max possible length
        seq += ["".join(x) for x in (zip(*(li[i:] for i in range(i)))) if " " not in x]
    return max([x  for x in seq if seq.count(x) > 1],key=len) # get longest len string that appears more than once
print conseq_sequences(s)
HIYourName=

答案 3 :(得分:0)

问题与http://acm.hdu.edu.cn/showproblem.php?pid=2459完全相同 解决方案是使用后缀数组或后缀树并使用rmq。