问题描述:
解答:
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) return 0;
if (haystack.isEmpty()) return -1;
if (haystack.length() == needle.length()) {
for(int i=0;i<needle.length();i++){
if(haystack.charAt(i)!=needle.charAt(i)){
return -1;
}
}
return 0;
}
char[] s_arr = haystack.toCharArray();
char[] t_arr = needle.toCharArray();
int[] next = getNextArray(t_arr);
int i = 0, j = 0;
while (i < s_arr.length && j < t_arr.length) {
if (j == -1 || s_arr[i] == t_arr[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j== t_arr.length) {
return i - j;
} else {
return -1;
}
}
public static int[] getNextArray(char[] t){
int[] next=new int[t.length];
next[0]=-1;
int k=-1;
int j=0;
while(j<t.length-1){
if(k==-1||t[j]==t[k]){
next[++j]=++k;
}else{
k=next[k];
}
}
return next;
}
}