鱼C论坛

 找回密码
 立即注册
查看: 2768|回复: 0

[技术交流] 字符串匹配(滚动Hash)

[复制链接]
发表于 2019-4-6 22:03:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>

const int seed = 31;
using namespace std;

long long hash(string &s)
{
    long long hash_code = 0;
    for(int i=0; i<s.size()-1; ++i){
        hash_code = ((hash_code + s.at(i)) * seed) % __LONG_LONG_MAX__;
    }
    hash_code = (hash_code + s.at(s.size()-1)) % __LONG_LONG_MAX__;
    return hash_code;
}

void RabinKarp(string &source, string &pattern)
{
        if(source.size()<pattern.size())
        {
                cout << "Error" << endl;
                return;
        }
        long long hash_pattern = hash(pattern);
        long long old_hash = 0;
        string begin = source.substr(0, pattern.size());
        old_hash = hash(begin);
        if(old_hash == hash_pattern)
                cout << "begin_index: " << 0 << endl;
        for(int i=1; i<=source.size()-pattern.size(); ++i)
        {
                old_hash = (old_hash - source.at(i-1) * pow(seed, pattern.size()-1)) * seed + source.at(i+pattern.size()-1);
                if(old_hash == hash_pattern)
                        cout << "begin_index: " << i << endl; 
        }        
} 

int main()
{
        string a, b;
        cin >> a >> b;
        RabinKarp(a, b);        
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-2-24 22:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表