函数get_nextval(char T[], int nextval[])是计算字符串T的next数组,函数Index_KMP(char S[], char T[], int pos, int next[])是KMP算法。
函数接口定义:
void get_nextval(char T[], int next[]); int Index_KMP(char S[], char T[], int pos, int next[]);
其中
T
是模式串,S
是主串,next
是next数组。裁判测试程序样例:
#include<cstring> #include<iostream> using namespace std; #define MAXSTRLEN 255 void get_nextval(char T[], int next[]); int Index_KMP(char S[], char T[], int pos, int next[]); int main() { char S[MAXSTRLEN+1],T[MAXSTRLEN+1]; char S1[MAXSTRLEN],S2[MAXSTRLEN]; cin >> S1 >> S2; strcpy(&S[1],S1); strcpy(&T[1],S2); S[0]=strlen(S1); T[0]=strlen(S2); int *next = new int[T[0]+1]; get_nextval(T,next); cout<<Index_KMP(S,T,1,next); return 0; } /* 请在这里填写答案 */
输入样例:
第一行输入主串,第二行输入模式串:
abdsegdsagddfddfedfgds egdsa
输出样例:
输出子串在主串中第p个位置后首次出现的位序:
5
void get_nextval(char T[], int next[]) {
next[1] = 0;
for(int i=2; i<=T[0]; i++) {
int x = next[i-1];
while(x && T[i] != T[x+1]) x = next[x];
if(T[i] == T[x+1]) ++x;
next[i] = x;
}
}
int Index_KMP(char S[], char T[], int pos, int next[]) {
int x = 0;
for(int i=pos; i<=S[0]; i++) {
if(S[i] == T[x+1]) {
++x;
if(x == T[0]) return i-T[0]+1;
continue;
}
while(x && T[x+1] != S[i]) x = next[x];
if(T[x+1] == S[i]) ++x;
}
}