下边是Sunday算法的流程:
1. i,j分别指向源串和模式串首, m指向源串中与模式串长度相等的后一位置m= i + t.size();
2. 滑动i,j, j == t.size() - 1,则返回,失配则执行3
1. i,j分别指向源串和模式串首, m指向源串中与模式串长度相等的后一位置m= i + t.size();
2. 滑动i,j, j == t.size() - 1,则返回,失配则执行3
3. 向右滑动模式串直到找到一个与m匹配的位置,重新设置i为当前与模式串首字符对齐的字符在源串的位置, m= i + t.size(),执行2
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int SundaySearch(string s,string t){
int sn=s.size();
int tn=t.size();
if(sn<=0||tn<=0)
return -1;
int i=0,j=0,k;
int m=tn;
for(;i<sn;){
if(s[i]!=t[j]){
for(k=tn-1;k>=0;k--){
if(t[k]==s[m])
break;
}
i=m-k;
j=0;
m=i+tn;
}
else{
if(j==tn-1)
return i-j;
i++;
j++;
}
}
}
int main(){
string s,t;
cin>>s>>t;
cout<<SundaySearch(s,t)<<endl;
return 0;
}