描述


字符串查找是计算机实现计算的基本问题,其解决方法很多。
假设现要编制一个满足下列要求的程序:在主串S中查找,是否存在一个子串T,如果存在则输出子串T在主串S中的位置,否则输出0。

请用如下函数完成上述功能,相关结构的定义如下(强烈建议使用下面的定义和函数结构)
typedef struct{
char *ch;
int length;
}String;

int Index(String S,Stirng T,int pos)



输入



每个测试数据包括2行,第一行为主串S,第二行为子串T,第三行为一个整数,表示开始查找的位置。


输出



针对每个测试数据进行处理,如果T在S中找到,则输出第一个找到的位置,否则输出0


样例输入


S = 'GGFHAQTDVNSI'
T = 'S'
1
S = 'CCCC'
T = 'C'
1
S = 'CC4C5C1'
T = 'W'
1


样例输出


Index(S, T, 1) = 11
Index(S, T, 1) = 1
Index(S, T, 1) = 0






#include<iostream>
#include<stdlib.h>
#include<cstring>
#include<stdio.h>
#include<malloc.h>
#define MX 5000
using namespace std;
typedef struct{
char *ch;
int length;
}String;
int next[1000];
int Next(String T)
{
next[1]=0;
next[2]=1;
for(int i=3;i<=T.length;i++){
int j=next[i-1];
while(j!=0&&T.ch[i-1]!=T.ch[j])
j=next[j];
next[i]=j+1;
}
}
int Index(String S,String T,int pos)
{
int i,j;
pos--;
j=1;
i=pos;
while(i<=S.length && j<=T.length)
{
if(S.ch[i-1]==T.ch[j-1]||j==0){
i++;j++;
}
else j=next[j];
}
if(j>T.length)
return i-pos-j+1;
return 0;
}
int input(String &s)
{
char a;
cin>>a>>a;
cin>>s.ch;
}
int main()
{
String S,T;
S.ch=(char *)malloc(MX*sizeof(char));
T.ch=(char *)malloc(MX*sizeof(char));
char a;
int pos;
while(cin>>a)
{
input(S);
S.length=strlen(S.ch);
S.ch[--S.length]='\0';
cin>>a;
input(T);
T.length=strlen(T.ch);
T.ch[--T.length]='\0';
Next(T);
cin>>pos;
printf("Index(S, T, %d) = %d\n",pos,Index(S,T,pos));
}
return 0;
}