next数组中保存的是匹配失败时所要回退的位置,
#include
using namespace std;
#define Maxsize 10
int main(){
void Next(string,int next[]);
int gets(string str,string s,int next[]);
int pos = 0;
string str = “aabcadsjaabcabx”;
string s = “abcabx”;
int next[Maxsize];
Next(s,next);
pos = gets(str,s,next);
cout<<pos<<endl;
return 0;
}
void Next(string s, int next[]){
int i = 1,k = -1;
next[0] = -1;
for(i = 1; i < s.length();i++){
while(k > -1 && s[i] != s[k+1]){ //next数组
k = next[k];
}
if(s[i] == s[k+1]){
k = k + 1;
}
next[i] = k;
}
}
int gets(string str,string s,int next[]){
int k = -1;
for(int i = 0; i < str.length();i++){
if(str[i] == s[k+1]){ //开始比较
k++;
if(k == s.length() - 1){ //若出现了,返回字符串在被匹配串的位置
return (i - k + 1);
}
}
else{
if(k > -1){
k = next[k];
i–;
}
else{
k = -1;
}
}
}
return 999; //若没有匹配成功,返回999
}