字符串匹配sunday算法c++实现(转)

本文详细介绍了一种基于模式匹配的周日算法实现,包括其核心数据结构BadChar表的构建过程及模式匹配流程。通过具体代码示例展示了如何使用C++实现该算法,并提供了一个完整的示例程序用于匹配字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载于http://blog.youkuaiyun.com/eqmcc/article/details/8205249

sunday.h

#include <cstdlib>
#include <string>
#include <iostream>
#include <map>

#ifndef _SUNDAYDLL_H_
#define _SUNDAYDLL_H_

using namespace std;

class Sunday{

    public:
    Sunday(string & _pattern){
        pattern=_pattern;
        pattern_length = pattern.size();
        match_offset=-1;
    }
    ~Sunday(){}

    // build the Bad char table using a map,计算模式串要移动的距离
    void build_BC(){
        for(int i=0;i<pattern_length;++i){
                BC[pattern[i]]=pattern_length-i-1;//用了map
            }
    }

    void show_BC(){
        map<char,int>::iterator it= BC.begin();
        while(it != BC.end()){
            cout<<"["<<it->first<<"]=>"<<it->second<<"\t"<<endl;
            ++it;
        }
    }

    int calc_jump(int i){
        map<char,int>::iterator it= BC.find(text[i]);
        return (it==BC.end())?pattern_length:it->second;
    }

    void match(string & _text){
        text=_text;
        int text_length=text.size();
        int i=pattern_length-1;
        int pos=pattern_length-1;
        match_offset=pattern_length-1;
        while(pos<=text_length){
            while(i>=0 && pattern[i]==text[pos]){--i;--pos;}
            if(i<0){cout<<"match at offset: "<<match_offset-pattern_length+1<<endl;return;}
            else{
                pos=match_offset+1;
                int jump=calc_jump(pos);
                pos=pos+jump;
                if(pos>text_length){cout<<"no match"<<endl;}
                i=pattern_length-1;
                match_offset=pos;
            }
        }
    }



    private:
    map<char,int> BC; // Bad Char map
    string pattern,text;
    int pattern_length;
    int match_offset;
};

#endif /* _SUNDAYDLL_H_ */

sunday.c

#include <cstdlib>
#include <string>
#include <iostream>
#include "sunday.h"

int main()
{
    string pattern = "search";
    string text = "substring searching algorithm";
    cout<<"pattern: "<<pattern<<endl;
    cout<<"text: "<<text<<endl;
    Sunday * sunday = new Sunday(pattern);
    sunday->build_BC();
    //sunday->show_BC();
    sunday->match(text);
    return 0;
}

 

转载于:https://www.cnblogs.com/cmjason/p/3910550.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值