给定字符串S和匹配串T,请你求出匹配串T在S中第一次正确匹配的索引位置。若匹配失败则返回0。
- 如题,C++版本的KMP代码模版如下:
样例输入
string str
thisisalongstring isa
nosubstring subt
样例输出
1
5
0
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAXN=102;
void get_next(char *T, int *next) {
int i = 1;
next[1] = 0;
int j = 0;
int Tlen=strlen(T+1);
while (i < Tlen) {
if (j == 0 || T[i] == T[j]) {
++i;
++j;
next[i] = j;
} else
j = next[j];
}
}
int Index_KMP(char *S, char *T, int pos) {
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置的
// KMP算法。其中,T非空,1≤pos≤StrLength(S)。
int next[255];
int i = pos;
int j = 1;
get_next(T, next);
int Slen=strlen(S+1);
int Tlen=strlen(T+1);
while (i <= Slen && j <= Tlen) {
if (j == 0 || S[i] == T[j]) { // 继续比较后继字符
++i;++j;
}else j = next[j]; // 模式串向右移动
}
if (j > Tlen) return i - Tlen; // 匹配成功
else return 0;
}
int main()
{
char s[MAXN],t[MAXN];
while(~scanf("%s%s",s+1,t+1)){
printf("%d\n",Index_KMP(s,t,1));
}
return 0;
}