shift and与shift or字符串匹配算法

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' 
 }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值