Shift-And 与 Shift-Or算法
当模式字符串长度数比机器字短和总字符集个数比较少时,Shift-And与Shift-Or算法平均效率是KMP的两倍,下面是Shift-And算法,Shift-Or是同样我思想,只不过用位0表示真状态
1 #include <cstdio>
2 #include <cstring>
3
4 void shiftAnd(char *t, char *p)
5 {
6 int lenP = strlen(p);
7 int b[26] = {0};
8 for(int i = 0; p[i]; ++i)
9 {
10 b[p[i] - 'a'] |= 1 << i;
11 }
12
13 int status = 0;
14 for(int i = 0; t[i]; ++i)
15 {
16 status = ((status << 1) | 1) & b[t[i] - 'a'];
17 if(status & (1 << (lenP - 1)))
18 printf("%d\n", i - lenP + 1);
19 }
20 }
21
22 int main()
23 {
24 char T[100];
25 char P[32];
26 scanf("%s%s", T, P);
27 shiftAnd(T, P);
28 return 0;
29 }
浙公网安备 33010602011771号