#include <iostream>
#include <string>
#include <vector>
using namespace std;
void getNextArr(string& str2, vector<int>& next) {
next.at(0) = -1;
if (str2.length() == 1) {
return;
}
next.at(1) = 0;
for (int cn = 0, i = 2; i < str2.length(); i++) {
if (str2.at(i - 1) == str2.at(cn)) {
next.at(i++) = ++cn;
}
else if (cn == 0) {
next.at(i++) = 0;
}
else {
cn = next.at(cn);
}
}
}
int KMP(string& str1, string& str2) {
if (str1.empty() || str2.empty() || str1.length() < str2.length()) {
return -1;
}
vector<int> next(str2.length(), 0);
getNextArr(str2, next);
size_t len1 = 0;
size_t len2 = 0;
while (len1 < str1.length() && len2 < str2.length()) {
if (str1.at(len1) == str2.at(len2)) {
len1++;
len2++;
}
else if (next.at(len2) == -1) {
len1++;
}
else {
len2 = next.at(len2);
}
}
return len2 == str2.length() ? (len1 - len2) : -1;
}
int main() {
string str1("abkabkacbck");
string str2("cb");
int res = KMP(str1, str2);
cout << res << endl;
system("pause");
return 0;
}
如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢