Chinaunix首页 | 论坛 | 博客
  • 博客访问: 516177
  • 博文数量: 118
  • 博客积分: 10028
  • 博客等级: 上将
  • 技术积分: 1820
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-07 18:46
文章分类

全部博文(118)

文章存档

2009年(12)

2008年(106)

我的朋友

分类:

2009-05-20 20:02:08


修改后使得BM算法作为一个接口而存在,直接调用BMSearch()就可以了,测试只需要定义一个测试宏就行,用的时候注释掉~ 接口的参数代码里都注释清楚了~


/*
* the boyer-moore algorithm
* for text search of rules cotent
* by zuii||williamzuii@163.com
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BM_TEST

#define LEN 256

/*
 * BMMatch()
 * match once for each call,if match succeed,return 0
 * or else,return the index for the next match
 *
 */

int BMMatch(const char *src,const char *pattern,int idx,int po[])
{
    const int slen=strlen(src);
    int i=strlen(pattern)-1;
    int j=idx+i;
    int nidx;
    
    if(j > slen)
        return -1;
        
    for(;i>=0;i--,j--){
        if(src[j] != pattern[i])
            break;
    }
    
    if(i < 0)
        return 0; /* match succeed */
    else if(po[src[j]] > 0) /* the charector is contained in pattern */
        nidx=idx+(i-po[src[j]]);
    else /* the charector is not contained in pattern */
        nidx=idx+i+1;
        
    return nidx;
}

/*
 * BMSearch()
 * --- the interface of the text search algorithm---Boyer-moore
 * Arguments:
 * src:the long text for matching with pattern
 * pattern: the pattern text use to match with src
 * n: the beginning char for matching in src
 * Return:
 * 0: matching succeed
 * -1:matching failed
 */

int BMSearch(const char *src,const char *pattern,int n)
{
    int po[LEN]={0};
    int i,idx=-2,nidx=n;
    int plen=strlen(pattern);
    if((n+strlen(pattern)) > strlen(src)){
        printf("Ivalid search!\n");
        return -1;
    }
        
    /* assistant array */
    for(i=0;i < plen;i++)
        po[pattern[i]]=i;
  
    /* the first time to match */
    idx=BMMatch(src,pattern,n,po);

    /* start looping */
    while(idx != -1 && idx != 0){
        nidx=idx;
        idx=BMMatch(src,pattern,nidx,po);
    }
    
    /* return 0 or -1 */
    return idx;
}

#ifdef BM_TEST
int main(int argc,char **argv)
{
    if(BMSearch("it's a test!Oh yeah!","test",4) == 0){
        printf("Succeed!\n");
    }else{
        printf("No content!\n");
    }
    
    //getch();

    return 0;
}
#endif

阅读(1115) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-02-01 10:12:43

这哪是bm算法呀