今天复习到王道的模式匹配,练一下自己的理解程度,编写了一个C++的实现程序
#include<iostream>
#include<string>
using namespace std;
int Index(string x,string y);
int main(){
string a,b;
cin>>a;
getchar();
cin>>b;
int x=Index(a,b);
cout<<x<<endl;
return 0;
}
int Index(string x,string y){
int i=0,j=0;
while(i<x.length()&&j<y.length()){
if(x[i]==y[j]){
i++;j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j>=y.length()) return i-y.length()+1; //在x中找到模式串y,返回在x中的位序
else return 0; //匹配失败,返回0
}