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


    转载于http://blog.csdn.net/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<<"	"<<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;
    }
    因为弱小,所以要变强,因为不想灭亡,所以选择战斗
  • 相关阅读:
    Windows2016修改密码
    Linux设置文件夹的权限
    Linux防火墙的命令
    Linux安装jdk1.8.0_181
    Linux删除,重命名文件夹和文件的命令
    一次循环打印九九乘法表
    java垃圾回收机制
    操作系统常用调度算法
    Android中TextView中的文字设置为不同颜色
    自定义Dialog以及Dialog返回值到Activity
  • 原文地址:https://www.cnblogs.com/cmjason/p/3910550.html
Copyright © 2020-2023  润新知