#include<iostream>
#include<string.h>
using namespace std;
void get_next(string str, int* next) {
int pre = -1;
int tail = 0;
next[0] = -1;
while (tail < str.size() - 1) {
if (pre == -1 || str[pre] == str[tail]) {
pre++;
tail++;
next[tail] = pre;
}
else {
pre = next[pre];
}
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) return 0;
int i = 0;
int j = 0;
int next[255];
get_next(needle, next);
/* int length_s = haystack.size();
int length_t = needle.size();*/
while (i < (int)haystack.size() && j < (int)needle.size()) //如果while(i < haystack.size() && j < needle.size()),出现不可预料的错误
{
if (j == -1 || haystack[i] == needle[j]) {
i++;j++;
}
else j = next[j];
}
if (j >= needle.size()) {
return i - needle.size();
}
else
return -1;
}
void main() {
cout << strStr("hello","ll")<< endl;
while (1);
}
KMP算法实现
最新推荐文章于 2025-04-20 17:57:03 发布