LeetCode-Implement strStr()-KMP

时间:2023-03-08 15:23:56
LeetCode-Implement strStr()-KMP

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition.

Solution:

 public class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) return 0;
if (haystack.isEmpty()) return -1; int[] pm = getPartialMatchTable(needle);
int p1 = 0, p2 = 0;
while (p1<haystack.length() && p2<needle.length()){
if (haystack.charAt(p1)==needle.charAt(p2)){
p1++;
p2++;
} else {
if (p2==0) p1++;
else p2 = pm[p2-1]+1;
}
}
if (p2<needle.length()) return -1;
else return p1-p2; } public int[] getPartialMatchTable(String needle){
int[] pm = new int[needle.length()];
pm[0] = -1;
for (int i=1;i<needle.length();i++){
int j = pm[i-1];
while (j>=0 && needle.charAt(i)!=needle.charAt(j+1)) j = pm[j];
if (needle.charAt(i)==needle.charAt(j+1)) pm[i] = j+1;
else pm[i] = -1;
}
return pm;
}
}