字符串匹配之位并行算法Shift-Or
程序代码:// 位并行算法Shift-Or算法
// 1、对模式串构造掩码表设模式串为abacb
// a b a c b的掩码表为
// a 1 0 1 0 0
// b 0 1 0 0 1
// c 0 0 0 1 0
// 2、置D = 0, 对于新输入文本字符szMsg[j],
// 用公式D >> 1 | 2^(len-1) & Bset[Index]-> D
// if szMsg[j] = a or A Then Index = 0 Bset[Index] = 20
// 3、如果D&1==1当前的模式串与文本的以j个为结尾
// 的最后len个字符匹配.str[0]...str[len-1] = szMsg[j-len+1]..szMsg[j]
#include <stdio.h>
#include <string.h>
#include <math.h>
const int MAX_LEN = 256;
// 创建位掩码集合
void CreateBset(char *str, int Bset[])
{
int len = strlen(str);
int i;
int j;
for (i=0; i<26; i++)// 行26 a到z
{
for (j=0; j<len; j++)
{
if (i == (str[j] - 'A')%32)//大小写一样匹配字母对应数字映射
{
Bset[i] += (int)pow((double)2, (double)(len-1-j)); //出现的就是1
}
}
}
return;
}
int main()
{
char str[256] = {0};
char szMsg[1024] = {0};
//输入模式串
gets(str);
//输入文本
gets(szMsg);
int len = strlen(str);
int Bset[26] = {0};
int D = 0;//位掩码
int Index;
//创建掩码表集合
CreateBset(str, Bset);
int j = 0;
int count = 0;
while(j<strlen(szMsg))
{
D = (D >> 1) | (int)pow((double)2, (double)(len - 1));//右移1或上最高位为1
Index = szMsg[j] - 'A';
D = D & Bset[Index%32];//读入的文本的掩码集&上D
if (1 == (D&1))//如果D的二进制第一位为1目标匹配
{
count++;//匹配的个数
}
j++;
}
printf("匹配的个数%d\n", count);
return 0;
}









