这是我的代码和测试用例。我的问题是,似乎KMP模式的价值永远不会增加,因为在上一次迭代中,我们检查了pattern[i] != pattern[j]
,并且在当前轮次中if (j == -1) or (pattern[j] == pattern[i])
不能为真,除非j == -1
?
def findPattern(pattern):
j = -1
next = [-1] * len(pattern)
i = 0 # next[0] is always -1, by KMP definition
while (i+1 < len(pattern)):
if (j == -1) or (pattern[j] == pattern[i]):
i += 1
j += 1
if pattern[i] != pattern[j]:
next[i] = j
else:
next[i] = next[j]
else:
j = next[j]
return next
if __name__ == "__main__":
# print findPattern("aaaab")
print findPattern("abaabc")
提前谢谢,
林
答案 0 :(得分:1)
您已经增加了i和j,因此您实际上在pattern[i+1] != pattern[j+1]
之后检查了if (j == -1) or (pattern[j] == pattern[i])