代码
#include <iostream>
#include <cstring>
using namespace std;
int* GetNext(char* p);
//暴力匹配
int ViolentMatch(char* s,char* p) {
int sLen = strlen(s);
int pLen = strlen(p);
int i = 0, j = 0;
while (i < sLen && j < pLen) {
if (s[i] == p[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j == pLen)
return i - j;
return -1;
}
//KMP
int KmpMatch(char* s,char* p) {
int sLen = strlen(s);
int pLen = strlen(p);
int i = 0, j = 0;
int* next = GetNext(p);
//cout << sLen << ' ' << pLen << endl;
while (i < sLen && j < pLen) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
}
else
{
j = next[j];
}
}
if (j == pLen)
return i - j;
return -1;
}
int* GetNext(char *p){
int pLen = strlen(p);
int* next = new