Here is my code and test case. My question is, it seems the value of KMP pattern will never increase, since in last iteration, we checked pattern[i] != pattern[j], and in current round if (j == -1) or (pattern[j] == pattern[i]) cannot be true unless 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")
thanks in advance, Lin
findPattern(pattern)function, could you post what you expect? Also, it seems that codereview.stackexchange.com/questions/109281/… and codereview.stackexchange.com/questions/107909/… verified that you are getting indeed the correct output and improved your code.