28 实现 strStr()
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
理论懂了,实现里面不太懂,抄了一遍代码。
class Solution {
public int strStr(String haystack, String needle) {
int[] next = new int[needle.length()];
int j = -1;
next[0] = j;
for (int i = 1; i < needle.length(); i++) { //求next数组
while(j >= 0 && needle.charAt(i) != needle.charAt(j + 1)) {
j = next[j];
}
if (needle.charAt(i) == needle.charAt(j + 1)) {
j++;
}
next[i] = j;
}
j = -1;
for (int i = 0; i < haystack.length(); i++) { //匹配过程
while (j >= 0 && haystack.charAt(i) != needle.charAt(j + 1)) {
j = next[j];
}
if (haystack.charAt(i) == needle.charAt(j + 1)) {
j++;
}
if (j == needle.length() - 1) {
return (i - needle.length() + 1);
}
}
return -1;
}
}