时间复杂度:O(n^2)
#include <iostream>
#include<stdlib.h>
#include<string>
#include<stdio.h>
using namespace std;
#define STR "hedateMjidvfdvdvfvrhtdfvjsafnfui\
wfkvjvikwafehwfiIAJVDIVEOGXDiokgtkbdifvejrevdk\
vdgegivdgirestructpleasestudyit"
int KMP_fun1(string str1, string str2)
{
int nSize_1 = str1.size();
int nSize_2 = str2.size();
int i = 0;
int j = 0;
int nlen_str2 = nSize_2 - 1;
while (i < nSize_2) //保持子串
{
while (j < nSize_1)
{
if (str2[i] == str1[j]) //让母串逐一去匹配子串
{
i++;
j++;
if (i == nSize_2-1)
{
return j- nlen_str2;
}
}
else {
j++;
i = 0;
}
}
break;
}
return -1;
}
int main()
{
string str1(STR);
string str2("nfuiwfkvjvikwafeh");
int num = KMP_fun1(str1,str2);
cout << num << endl;
return 0;
}