ACM -- 算法小结(五)字符串算法之Sunday算法

时间:2022-08-18 10:52:10

1. Sunday算法是Daniel M.Sunday于1990年提出的一种比BM算法搜索速度更快的算法。

2. Sunday算法其实思想跟BM算法很相似,只不过Sunday算法是从前往后匹配,

在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符。

如果该字符没有在匹配串中出现则直接跳过,即移动步长= 匹配串长度+ 1;

否则,同BM算法一样其移动步长=匹配串中最右端的该字符到末尾的距离+1。

3. 举例如下:

//pos=0;
//匹配串:abcdacdaahfacabcdabcdeaa
//模式串:abcde
//这里我们看到a-e没有对上,我们就看匹配串中的pos+len2在模式串的位置,然后对齐。 //匹配串:abcdacdaahfacabcdabcdeaa
//模式串: abcde
//pos=3;
//这里我们看到d-a没有对上,我们就看匹配串中的pos+len2在模式串的位置,然后对齐。 //匹配串:abcdacdaahfacabcdabcdeaa
//模式串: abcde
//pos=8;
//这里我们看到h-b没有对上,我们就看匹配串中的pos+len2在模式串的位置,然后对齐。 //匹配串:abcdacdaahfacabcdabcdeaa
//模式串: abcde
//pos=13;
//这里我们看到c-b没有对上,我们就看匹配串中的pos+len2在模式串的位置,然后对齐。 //匹配串:abcdacdaahfacabcdabcdeaa
//模式串: abcde
//pos=17;
//这里我们看到模式串完全匹配

代码演示如下:

 #include <iostream>
#include <cstring>
using namespace std; char T[];
char P[];
int next[]; int sunday(const char* T, const char* P)
{
int len1=strlen(T);
int len2=strlen(P);
memset(next,,sizeof(next)); for(int j=; j<;++j)
next[j]=len2+;
for(j=; j<len2;++j)
{
next[P[j]-'a']=len2-j; //记录字符到最右段的最短距离+1
//cout<<"next["<<P[j]-'a'<<"]="<<next[P[j]-'a']<<endl;
}
//例如:p[]="abcedfb"
//next = {7 6 5 4 3 2 1 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8} int pos = ;
while(pos<(len1-len2+)) //末端对齐
{
int i=pos;
int j;
for(j=;j<len2;++j,++i)
{
if(T[i]!=P[j]) //不等于就跳跃,跳跃是核心
{
pos+= next[T[pos + len2]-'a'];
//cout<<"pos="<<pos<<endl<<endl;
break;
}
}
if(j==len2)
return pos;
}
return -;
}
int main()
{
char T[]="abcdacdaahfacabcdabcdeaa";
char P[]="abcde";
while(scanf("%s%s",T,P)!=EOF)
cout<<sunday(T,P)<<endl;
return ;
}