class Solution:
def cal_next(self, str, next):
k = -1
for i in range(1, len(next)):
while k > 0 and str[k + 1] != str[i]:
k = next[k]
if str[k + 1] == str[i]:
k += 1
next[i] = k
def KMP(self, str, pstr, next):
i, j = 0, 0
self.cal_next(pstr, next)
for i in range(len(str)):
while j > 0 and pstr[j] != str[i]:
j = next[j - 1] + 1
if pstr[j] == str[i]:
j += 1
if j == len(pstr):
return i - len(pstr) + 1
return -1
if __name__ == "__main__":
test = Solution()
str = 'bacbababadababacambabacaddababacasdsd'
pstr = 'ababaca'
next = [-1] * len(pstr)
rlt = test.KMP(str, pstr, next)
print(rlt)