一、前缀蛮力匹配算法
模式串和母串的比较是从左到右进行(strncmp()),如果找不到和模式串相同的子串,则从左到右移动模式串,距离为1(s++)。
char * strstr(register const char *s, register constchar *wanted)
{
register const size_t len = strlen(wanted);
if (len ==0) return (char*)s;
while (*s !=* wanted || strncmp(s, wanted, len))
if (*s++=='\0')
return (char*)NULL;
return (char*)s;
}
二、KMP算法 、BM算法
三、sunday算法
1,Sunday算法是Daniel M.Sunday于1990年提出的一种比BM算法搜索速度更快的算法。
2,Sunday算法其实思想跟BM算法很相似,只不过Sunday算法是从前往后匹配,在匹配失败时关注的是文本串中参加匹配的最末位字符的下一位字符。如果该字符没有在匹配串中出现则直接跳过,即移动步长= 匹配串长度+ 1;否则,同BM算法一样其移动步长=匹配串中最右端的该字符到末尾的距离+1。
3,举例:
匹配串:abcbczdxzc
模式串:zbcac
这里我们看到z-a没有对上,我们就看匹配串中的z在模式串的位置,然后对齐。
匹配串:abcbczdxzc
模式串: zbcac
如果模式串中的没有那个字符的话就跳过去。
匹配串:abcbcedxzcs
模式串:zbcac
e不在模式串中出现,那么我们就
匹配串:abcbcedxzcs
模式串: zbcac
//字符串模式匹配 sunday 算法
#include <iostream>
#include <cstring>
#define array_size 26
using namespace std;
int sunday(const char* ori, const char* patt)
{
int len_s = strlen(ori);
int len_d = strlen(patt);
int jump[array_size] = {0};
for (int j = 0; j < array_size; ++j)
jump[j] = len_d + 1;
for (int j = 0; j < len_d; ++j)
jump[patt[j] - 'a'] = len_d - j; //记录字符到最右段的最短距离+1
//例如:des = "abcedfb"
//next = {7 1 5 4 3 2 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8}
int pos = 0;
while (pos < (len_s - len_d + 1)) //末端对齐
{
int i = pos;
int j = 0;
for (j = 0; j < len_d; ++j, ++i)
{
if (ori[i] != patt[j])
{
pos += jump[ori[pos + len_d] - 'a'];
//不等于就跳跃,跳跃是核心
break;
}
}
if (j == len_d)
return pos;
}
return -1;
}
int main()
{
char ori[]="abcdacdaahfacabcdabcdeaa";
char patt[]="abcde";
cout<<sunday(ori,patt)<<endl;
return 0;
}