描述
字符串查找是计算机实现计算的基本问题,其解决方法很多。
假设现要编制一个满足下列要求的程序:在主串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
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
Index(S, T, 1) = 1
Index(S, T, 1) = 0
题解: KMP算法的运用,这个题坑,第二个字符可能为空字符。
AC code:
#include <iostream> #include <string> using namespace std; #define MAX 10000 typedef struct{ char *ch; int length; }String; int next[MAX]; // next函数 void get_next(String T) { int i=1,j=0; next[1]=0; while(i<T.length) { if(j==0 || T.ch[i]==T.ch[j]) { ++i; ++j; next[i]=j; } else j=next[j]; } } // KMP 算法 int Index(String S,String T,int pos) { int i=pos,j=1; while(i<=S.length && j<=T.length) { if(j==0 || S.ch[i]==T.ch[j]) { ++i; ++j; } else j=next[j]; } if(j>T.length) return i-T.length; return 0; } int main() { String S,T; char s[MAX],str[10],s1[MAX]; int n,t,i; while(cin>>str) { cin>>str; gets(s); //初始化 S.ch=new char[MAX]; T.ch=new char[MAX]; int l1,l2; l1=strlen(s); S.length=1; //这里是从1开始的 for(i=1;i<l1;i++) { if(s[i]!='\'') // ’为转意字符 S.ch[S.length++]=s[i]; } cin>>str; cin>>str; gets(s1); cin>>n; l2=strlen(s1); if(l2==3) // 第二个字符可能为空 { cout<<"Index(S, T, "<<n<<") = "<<0<<endl; continue; } T.length=1; //这里是从1开始的 for(i=1;i<l2;i++) { if(s1[i]!='\'') T.ch[T.length++]=s1[i]; } S.length-=1; //这里要减去1 T.length-=1; get_next(T); t=Index(S,T,n); cout<<"Index(S, T, "<<n<<") = "<<t<<endl; } return 0; }