String Match with KMP Algorithm
Search if a given string pattern (needle) is part of a target string (haystack) is a common problem. The naive approach is to use two nested loops with O(n * m) time complexity. KMP is a better way which has a better performance.
Two keypoints to implement KMP algorithm:
a. Generate LPS (Longest common proper Prefix and Suffix ) dictionary
b. Use LPS dictionary to identify a better pointer position for next matching instead of steping back.
28. Implement strStr()
1 | func strStr(haystack string, needle string) int { |
459. Repeated Substring Pattern
Since we can get the longest common prefix suffix by using KMP. For a string, if its LPS[n - 1] != -1, it means it has common prefix and suffix. So with this in mind, we can check len(s) % (len(s) - lps[-1] + 1)
.
1 | func repeatedSubstringPattern(s string) bool { |
1392. Longest Happy Prefix
Same as above, we can quickly get the LPS slice and check lps[n-1]
1 | func longestPrefix(s string) string { |
214. Shortest Palindrome
a. A naive brute-force solution will be :
1 | func shortestPalindrome(s string) string { |
b. Based on the solution a, s[:n - i] == reverted[i:]
, we want to find LPS in s + '#' + reverted
.
1 | func shortestPalindrome(s string) string { |
- https://leetcode.com/problems/repeated-substring-pattern/discuss/827070/Python-O(n)-Practice-KMP
- https://www.youtube.com/watch?v=4jY57Ehc14Y&t=857s
- https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0028.%E5%AE%9E%E7%8E%B0strStr.md
- https://leetcode.com/problems/shortest-palindrome/discuss/60113/clean-kmp-solution-with-super-detailed-explanation
- https://leetcode.com/problems/shortest-palindrome/solution/