https://leetcode.com/problems/implement-strstr/
- String
- Pattern Matching
Build failure function (LPS array) to handle mismatches efficiently without restarting.
O(n + m)
O(m)
class Solution {
public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
int[] lps = new int[needle.length()];
for (int i = 1; i < needle.length(); i++) {
int j = lps[i - 1];
while (j > 0 && needle.charAt(i) != needle.charAt(j)) j = lps[j - 1];
if (needle.charAt(i) == needle.charAt(j)) j++;
lps[i] = j;
}
int j = 0;
for (int i = 0; i < haystack.length(); i++) {
while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = lps[j - 1];
if (haystack.charAt(i) == needle.charAt(j)) j++;
if (j == needle.length()) return i - j + 1;
}
return -1;
}
}