鱼C论坛

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

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

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

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

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

x
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4. #include <cmath>

  5. const int seed = 31;
  6. using namespace std;

  7. long long hash(string &s)
  8. {
  9.     long long hash_code = 0;
  10.     for(int i=0; i<s.size()-1; ++i){
  11.         hash_code = ((hash_code + s.at(i)) * seed) % __LONG_LONG_MAX__;
  12.     }
  13.     hash_code = (hash_code + s.at(s.size()-1)) % __LONG_LONG_MAX__;
  14.     return hash_code;
  15. }

  16. void RabinKarp(string &source, string &pattern)
  17. {
  18.         if(source.size()<pattern.size())
  19.         {
  20.                 cout << "Error" << endl;
  21.                 return;
  22.         }
  23.         long long hash_pattern = hash(pattern);
  24.         long long old_hash = 0;
  25.         string begin = source.substr(0, pattern.size());
  26.         old_hash = hash(begin);
  27.         if(old_hash == hash_pattern)
  28.                 cout << "begin_index: " << 0 << endl;
  29.         for(int i=1; i<=source.size()-pattern.size(); ++i)
  30.         {
  31.                 old_hash = (old_hash - source.at(i-1) * pow(seed, pattern.size()-1)) * seed + source.at(i+pattern.size()-1);
  32.                 if(old_hash == hash_pattern)
  33.                         cout << "begin_index: " << i << endl;
  34.         }       
  35. }

  36. int main()
  37. {
  38.         string a, b;
  39.         cin >> a >> b;
  40.         RabinKarp(a, b);       
  41.     return 0;
  42. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 08:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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