题目链接
思路:使用KMP算法进行求解。
public int strStr(String haystack, String needle) {
if (needle.equals("")) {
return 0;
}
char[] hayChar = haystack.toCharArray();
char[] needleChar = needle.toCharArray();
int[] next = getNextArray(needleChar);
int i = 0;
int j = 0;
while (i < hayChar.length && j < needleChar.length) {
if (hayChar[i] == needleChar[j]) {
i++;
j++;
} else if (next[j] == -1) {
i++;
} else {
j = next[j];
}
}
return j == needleChar.length ? i - j : -1;
}
public int[] getNextArray(char[] arr) {
if (arr.length == 1) {
return new int[]{ -1 };
}
int[] next = new int[arr.length];
next[0] = -1;
next[1] = 0;
int i = 2;
int cn = 0;
while (i < arr.length) {
if (arr[i - 1] == arr[cn]) {
next[i++] = ++cn;
} else if (cn > 0) {
cn = next[cn];
} else {
next[i++] = 0;
}
}
return next;
}
也可以使用内置优化过的indexOf方法来进行求解。
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return -1;
}
if (needle.length() > haystack.length()) {
return -1;
}
if (needle.equals("")) {
return 0;
}
return haystack.indexOf(needle);
}