Knuth–Morris–Pratt algorithm, efficient single pattern searching algorithm.
Implementation
1 | def build(p): |
Exercises
1392. Longest Happy Prefix
using the KMP table.1
2
3
4
5
6
7
8
9
10
11def longestPrefix(self, s: str) -> str:
nxt = [0, 0]
j = 0
for i in range(1, len(s)):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
nxt.append(j)
return s[:nxt[-1]]