public class Solution {
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0)
return 0;
if(haystack == null || haystack.length() == 0)
return -1;
return kmp(haystack, needle);
}
public int kmp(String text, String pattern){
int[] next = getNext(pattern);
int k = -1;
for(int i = 0; i < text.length(); i++)
{
while(k >= 0 && pattern.charAt(k + 1) != text.charAt(i))
k = next[k];//不匹配强制左移动
if(pattern.charAt(k + 1) == text.charAt(i))
k++;
if(k == pattern.length() - 1)
return i - pattern.length() + 1;
}
return -1;
}
public int[] getNext(String source) {
int next[] = new int[source.length()];
int q, k; next[0] = -1; k = -1;
for(q = 1; q < source.length() ;q++)
{
while(k >= 0 && source.charAt(q) != source.charAt(k + 1))
k = next[k];
if(source.charAt(k + 1) == source.charAt(q))
k++;
next[q] = k;
}
return next;
}
}
public int strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0)
return 0;
if(haystack == null || haystack.length() == 0)
return -1;
return kmp(haystack, needle);
}
public int kmp(String text, String pattern){
int[] next = getNext(pattern);
int k = -1;
for(int i = 0; i < text.length(); i++)
{
while(k >= 0 && pattern.charAt(k + 1) != text.charAt(i))
k = next[k];//不匹配强制左移动
if(pattern.charAt(k + 1) == text.charAt(i))
k++;
if(k == pattern.length() - 1)
return i - pattern.length() + 1;
}
return -1;
}
public int[] getNext(String source) {
int next[] = new int[source.length()];
int q, k; next[0] = -1; k = -1;
for(q = 1; q < source.length() ;q++)
{
while(k >= 0 && source.charAt(q) != source.charAt(k + 1))
k = next[k];
if(source.charAt(k + 1) == source.charAt(q))
k++;
next[q] = k;
}
return next;
}
}