sunday算法发表于1990年,是一个比BM算法更有效的算法,在BM算法的发现者第一次发表该论文的时候论文题目为《A fast substring search algorithm》,有意思的是在 sunday算法发表的时候该论文的题目为《A very fast substring search algorithm》就多了一个单词。
写法一:
#include <iostream>
#include <cstring>
using namespace std;
int sunday(const char* src, const char* des)
{
int len_s = strlen(src);
int len_d = strlen(des);
int next[26] = {0};
for (int j = 0; j < 26; ++j)
next[j] = len_d + 1;
for (int j = 0; j < len_d; ++j)
next[des[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;
for (j = 0; j < len_d; ++j, ++i)
{
if (src[i] != des[j])
{
pos += next[src[pos + len_d] - 'a'];
//不等于就跳跃,跳跃是核心
break;
}
}
if ( j == len_d )
return pos;
}
return -1;
}
int main()
{
char src[]="abcdacdaahfacabcdabcdeaa";
char des[]="abcde";
cout<<sunday(src,des)<<endl;
return 0;
}
写法二:
char *qsearch(const char *text, int n, const char *patt, int m)
{
// get the length of the text and the pattern, if necessary
if (n < 0)
n = strlen(text);
if (m < 0)
m = strlen(patt);
if (m == 0)
return (char*)text;
// construct delta shift table
int td[128];
for (int c = 0; c < 128; c++)
td[c] = m + 1;
const char* p;
for (p=patt; *p; p++)
td[*p] = m - (p - patt);
// start searching...
const char *t, *tx = text;
// the main searching loop
while (tx + m <= text + n) {
for (p = patt, t = tx; *p; ++p, ++t) {
if (*p != *t) // found a mismatch
break;
}
if (*p == 0) // Yes! we found it!
return (char*)tx;
tx += td[tx[m]]; // move the pattern by a distance
}
return NULL;
}
写法三:
11 int in_dst(const char word, const char *dst)
12 {
13 int i = strlen(dst) - 1;
14
15 while (dst[i] != '\0')
16 {
17 if (dst[i] == word)
18 return (strlen(dst) - i);
19
20 i--;
21 }
22
23 return -1;
24 }
25
26
27 int sunday(const char *src, const char *dst)
28 {
29 int SrcLenth = strlen(src), DstLenth = strlen(dst);
30 int j = 0, i = 0, pos;
31
32 while (j < SrcLenth)
33 {
34 i = 0;
35 while (src[j+i] == dst [i])
36 {
37 i++;
38 continue;
39 }
40
41 if (dst[i] == '\0')
42 {
43 printf("%d~%d\n", j, j+DstLenth-1);
44 }
45
46 if ((pos = in_dst(src[j+DstLenth], dst)) != -1)
47 {
48 j += pos;
49 }
50 else
51 {
52 j += (DstLenth + 1);
53 }
54 }
55 }