What
Find the longest suffix which is also prefix in a string.
Idea
- Calculate the DP array
lsp[i]
= length of the lsp ends ati
- To calculate
lsp[i + 1]
, use previouslsp
:lsp[i]
is the longest match so farlsp[lspp[i]]
is the second longest- … so on
Implementation
Complexity
- Time:
- Space:
Application
- Use in KMP - Knuth-Morris-Pratt for linear time pattern matching:
compute_lsp(p + sep + t)
- Find the longest prefix palindrome:
compute_lsp(t + sep + t[: : -1])
Misc
- This has a similar spirit to Z-function.