KMP算法
关键在于如何求next数组
void getNext(int *next, const string &s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
// next[j + 1]指向匹配好的前缀的下一个字符
// i指向后缀末尾位置
while (j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;//j+1表示最长相等子串的长度,所以字符相等时,长度递增
}
next[i] = j;
}
}
完整代码
#include <string>
using std::string;
class Solution {
public:
void getNext(int *next, const string &s) {
int j = -1;
next[0] = j;
for (int i = 1; i < s.size(); i++) {
// next[j + 1]指向匹配好的前缀的下一个字符
// i指向后缀末尾位置
while (j >= 0 && s[i] != s[j + 1]) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0)
return 0;
int next[needle.size()];
getNext(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
//出现不等时,跳到最长相等子串的下一个字符处
while (j >= 0 && haystack[i] != needle[j + 1]) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == (needle.size() - 1))
return i - needle.size() + 1;
}
return -1;
}
};
标签:strStr,string,int,needle,next,++,str,implement,size
From: https://www.cnblogs.com/zwyyy456/p/16589662.html