shift and与shift or字符串匹配算法
本人菜鸟一名,刚接触算法,便啃了一块硬骨头。若有错误之处,欢迎乱喷!
算法实现:C
#include <string.h>//declare strlen(),memset()
int shift_and(const char* t,const char* p);//declaration
int shift_or(const char* t,const char* p);//declaration
//shift and algorithm
int shift_and(const char* t,const char* p)
{//t=Text,p=pattern,n=strlen(t),m=strlen(p)
int B[256];//256=2^8
memset(B, 0, sizeof(B));//initialize B[c] to 0
int n=strlen(t),m=strlen(p);
int D = 0;
//preprocessing
for (int i = 0; i < m; i++)
{
B[ p[i] ] |= (0x01 << i);//use 0x01 instead of 1,display clearly
}
//searching
for (int pos = 0; pos < n; ++pos)//pos=position
{
D=( (D << 0x01) | 0x01 ) & B[ t[pos] ];
if ( D & (0x01 << (m - 1)) )//D[m]=1
return pos - (m - 1)+1;//extra plus 1,pos from 0 to n-1
}
return -1;//not match 'p' in 't'
}
//shift or algorithm
int shift_or(const char* t,const char* p)
{//t=Text,p=pattern,n=strlen(t),m=strlen(p)
int B[256];//256=2^8
memset(B, ~0, sizeof(B));//initialize B[c] to ~0,contrary to shift_and
int n=strlen(t),m=strlen(p);
int D = ~0;//contrary to shift_and
//preprocessing
for (int i = 0; i < m; i++)
{
B[ p[i] ] ^= (0x01 << i);//contrary to shift_and
//the same as B[ p[i] ] |= ~(0x01 << i)
}
//searching
for (int pos = 0; pos < n; ++pos)//pos=position
{
D=(D << 0x01) | B[ t[pos] ];//less one time of bit computing than the previous
if ( ~(D | ~(0x01 << (m - 1)) ) )//D[m]=0
return pos - (m - 1)+1;//extra plus 1,pos from 0 to n-1
}
return -1;//not match 'p' in 't'
}