【KMP】kmp的板子题
class Solution {
public int strStr(String haystack, String needle) {
int m = haystack.length(), n = needle.length();
int N = 1001;
int[] ne = new int[N];
char[] s = new char[N], p = new char[N];
for (int i = 0; i < m; i++) s[i + 1] = haystack.charAt(i);
for (int i = 0; i < n; i++) p[i + 1] = needle.charAt(i);
for (int i = 2, j = 0; i <= n; i++) {
while (j != 0 && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
for (int i = 1, j = 0; i <= m; i++) {
while (j != 0 && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j++;
if (j == n) return i - n;
}
return -1;
}
}
class Solution {
public:
int strStr(string haystack, string needle) {
const int N = 1001;
int ne[N], m = haystack.length(), n = needle.length();
char s[N], p[N];
for (int i = 0; i < m; i++) s[i + 1] = haystack[i];
for (int i = 0; i < n; i++) p[i + 1] = needle[i];
for (int i = 2, j = 0; i <= n; i++) {
while(j && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
for (int i = 1, j = 0; i <= m; i++) {
while (j && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j++;
if (j == n) {
return i - n;
}
}
return -1;
}
};