// -------------------------------------
// KMP算法求目标串是否是源串的子串
// 是 返回position
// 否 返回-1
// -------------------------------------
#include <iostream>
#include <string>
using namespace std;
void GetNext(string s, int next[], int length) {
int i = 0;
int j = -1;
next[0] = -1;
while (i < length) {
if (j == -1 || s[i] == s[j]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
int IsSubString_Kmp(string source, string target) {
int pos = -1;
int sLen = source.length();
int tLen = target.length();
int i = 0, j = 0;
int *next = new int[tLen];
GetNext(target,next, tLen);
while (i < sLen&&j < tLen) {
if (j == -1|| target[j] == source[i]) {
i++;
j++;
}
else {
j = next[j];
}
}
if (j == tLen)
pos = i - tLen;
return pos;
}
int main() {
string s = "adsadsadadss", t = "adsada";
cout << IsSubString_Kmp(s, t) << endl;
system("pause");
return 0;
}