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.
实际为实现Java中indexOf(String str)方法;
package leetcode;
public class ImplementStr {
public staticint strStr(String haystack, Stringneedle) {
int ans = 0;
ans = haystack.indexOf(needle);
return ans;
}
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
}
}
KMP算法:
package leetcode;
import java.util.Arrays;
public class ImplementStr {
public static int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
/*
* KMP算法
*/
public int strStrByKMP(String haystack, String needle) {
int ans = -1;
// if (haystack.length() == 0) return ans;
if (needle.length() == 0)
return 0;
char[] s = haystack.toCharArray(); //source
char[] t = needle.toCharArray(); //target
int[] partialMatchTable = getPartialMatchTable(t); //部分匹配值
int i = 0;
int j = 0;
while (i <= s.length - 1 && j <= t.length - 1) {
System.out.println(j);
if (j == -1 || s[i] == t[j]) {
i++;
j++;
} else {
j = partialMatchTable[j];
}
}
if (j < t.length) {
return -1;
} else
return i - t.length; // 返回模式串在主串中的头下标
}
private int[] getPartialMatchTable(char[] t) {
// int i = 0, j = -1;
// int [] next = new int[t.length];
// next[0] = -1;
// while(i< t.length - 1) {
// if(j == -1 || t[i] == t[j]){
// ++i;
// ++j;
// if (t[i] != t[j]) {
// next[i] = j;
// } else {
// next[i] = next[j];
// }
// }
// else
// j = next[j];
// }
// System.out.println(Arrays.toString(next));
// return next;
// int i = 0, j = -1;
// int [] next = new int[t.length];
// next[0] = -1;
// while(i < t.length - 1) {
// if(j == -1 || t[i] == t[j]){
// ++i;
// ++j;
// next[i] = j;
// }
// else
// j = next[j];
// }
// System.out.println(Arrays.toString(next));
// return next;
int[] next = new int[t.length];
next[0] = -1;
int i = 0;
int j = -1;
while (i < t.length - 1) {
if (j == -1 || t[i] == t[j]) {
i++;
j++;
if (t[i] != t[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
System.out.println(Arrays.toString(next));
return next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(strStr("mississippi", "pi"));
System.out.println(new ImplementStr().strStrByKMP("mississippi", "pi"));
/*
*
模式串 a b a a b c a c
next值 0 1 1 2 2 3 1 2
nextval值 0 1 0 2 1 3 0 2
[-1, 0, -1, 1, 0, 2, -1, 1]
*/
}
}