KMP算法(前面的过程可以指导后面的过程)
//求字符串str1中是否包含str2
//1、求next数组(该字符前面的最长前缀和最长后缀相等的长度)
//2、根据next数组判断是否为字串
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
void GetNextArray(const string& str,int* nextarr)
{
int size = str.size();
nextarr[0] = -1;
if (size == 1)
return;
nextarr[1] = 0;
int i = 2;
int ch = nextarr[i-1];
while (i < size){
if (str[i - 1] == str[ch]){
nextarr[i++] = ++ch;
}
else if (ch > 0){
ch = nextarr[ch];
}
else{
nextarr[i++] = 0;
}
}
//while (i < size){
// if (ch == -1){
// ch = 0;
// nextarr[i++] = 0;
// }
// else if (str[i - 1] == str[ch]){
// nextarr[i++] = ++ch;
// }
// else{
// ch = nextarr[ch];
// }
//}
return;
}
int getIndexOf(const char* str1,const char* str2,int size1,int size2)
{
if (str1 == NULL || str2 == NULL || size2 < 1 || size1 < size2)
return -1;
//求next数组
int* nextarr = new int[size2];
GetNextArray(str2,nextarr);
int i = 0, j = 0;
while (i < size1 && j < size2){
if (j == 0 && str1[i] != str2[j])
++i;
else if (str1[i] == str2[j]){
++i, ++j;
}
else{
j = nextarr[j];
}
}
return j == size2 ? i - j : -1;
}
int main()
{
/*char* str1 = "deabctabctabcde";
char* str2 = "abctabcde";*/
//nextarr= -100001230
int index=getIndexOf(str1,str2,strlen(str1),strlen(str2));
cout << index << endl;
system("pause");
return 0;
}
转载于:https://blog.51cto.com/lingdandan/1853066