下标从0开始的kmp匹配
C++ 代码
class Solution {
public:
int strStr(string h, string p) {
if (p.empty()) return 0;
int n = h.length(), m = p.length();
vector<int> ne(m);
ne[0] = -1;
for (int i = 1, j = -1; i < m; i++)
{
while (j > -1 && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
for (int i = 0,j = -1; i < n; i++)
{
while (j > -1 && h[i] != p[j + 1]) j = ne[j];
if (h[i] == p[j + 1]) j++;
if (j == m - 1)
return i - m + 1;
}
return -1;
}
};