【发布时间】:2015-12-09 12:57:48
【问题描述】:
我必须实现 Z 算法并使用它在目标文本中搜索特定模式。我已经实现了我认为正确的算法和使用它的搜索功能,但它真的很慢。对于字符串搜索的幼稚实现,我始终得到低于 1.5 秒的时间,而对于 z 字符串搜索,我始终得到超过 3 秒的时间(对于我最大的测试用例),所以我必须做错事。结果似乎是正确的,或者至少对于我们给出的少数测试用例来说是正确的。我的咆哮中提到的功能的代码如下:
import sys
import time
# z algorithm a.k.a. the fundemental preprocessing algorithm
def z(P, start=1, max_box_size=sys.maxsize):
n = len(P)
boxes = [0] * n
l = -1
r = -1
for k in range(start, n):
if k > r:
i = 0
while k + i < n and P[i] == P[k + i] and i < max_box_size:
i += 1
boxes[k] = i
if i:
l = k
r = k + i - 1
else:
kp = k - l
Z_kp = boxes[kp]
if Z_kp < r - k + 1:
boxes[k] = Z_kp
else:
i = r + 1
while i < n and P[i] == P[i - k] and i - k < max_box_size:
i += 1
boxes[k] = i - k
l = k
r = i - 1
return boxes
# a simple string search
def naive_string_search(P, T):
m = len(T)
n = len(P)
indices = []
for i in range(m - n + 1):
if P == T[i: i + n]:
indices.append(i)
return indices
# string search using the z algorithm.
# The pattern you're searching for is simply prepended to the target text
# and than the z algorithm is run on that concatenation
def z_string_search(P, T):
PT = P + T
n = len(P)
boxes = z(PT, start=n, max_box_size=n)
return list(map(lambda x: x[0]-n, filter(lambda x: x[1] >= n, enumerate(boxes))))
【问题讨论】:
-
用 pypy 运行最简单
-
你最大的测试用例有多大?
-
例如在这种情况下 P:aaa T:aaaaaa 你的算法会产生不同的结果。
-
那你的问题是什么?
标签: python algorithm string-matching