力扣2156.查找给定哈希值的子串

力扣2156.查找给定哈希值的子串

  • rolling hash:求带权的值 左边是高位 右边是低位

    • 本题要求左边低位 只要反向求即可
  •   class Solution {
      public:
          string subStrHash(string s, int power, int modulo, int k, int hashValue) {
              int n = s.size();
              long long M = modulo,pk=1,hash = 0;
              //预处理k个 并求出p^k-1
              for(int i=n-1;i>=n-k;i--)
              {
                  hash = ((long long)hash*power + (s[i] - 'a' + 1)) % M;
                  if(i != n-k) pk = (long long)pk*power%M;
              }
              
              int pos = -1;
              if(hash == hashValue) pos = n-k;
              for(int i=n-k-1;i>=0;i--)
                  {
                  	//把右边高位减掉
                      hash = hash - (s[i+k] - 'a' + 1) * pk % M;
                  	//防止hash减完成负数
                      hash = (hash + M) %M;
                  	//整体左移(升高一位)
                      hash = hash * power % M;
                  	//加上左边低位
                      hash = (hash + s[i]-'a'+1) % M;
                      if(hash == hashValue){
                          pos = i;
                      }
                  }
              return s.substr(pos,k);
          }
      };
    

相关推荐

  1. 2156.查找给定

    2024-06-07 02:46:02       35 阅读
  2. --表+滑动块--串联所有单词

    2024-06-07 02:46:02       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 02:46:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 02:46:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 02:46:02       87 阅读
  4. Python语言-面向对象

    2024-06-07 02:46:02       96 阅读

热门阅读

  1. 策略模式结合Spring使用

    2024-06-07 02:46:02       25 阅读
  2. Scala编程基础4 类、对象、继承、特质

    2024-06-07 02:46:02       30 阅读
  3. [React]用 flushSync 同步更新 state

    2024-06-07 02:46:02       32 阅读
  4. Sass 详解

    2024-06-07 02:46:02       26 阅读
  5. linux c socket编程里SO_REUSEADDR的作用

    2024-06-07 02:46:02       34 阅读
  6. 【安卓基础】-- 消息机制 Handler

    2024-06-07 02:46:02       32 阅读
  7. lm studio 0.2.24国内下载模型

    2024-06-07 02:46:02       32 阅读
  8. 常见代码版本管理工具

    2024-06-07 02:46:02       33 阅读
  9. Android WebView升级

    2024-06-07 02:46:02       22 阅读
  10. 判断素数/质数

    2024-06-07 02:46:02       29 阅读
  11. Loguru,一个 Python 日志神器

    2024-06-07 02:46:02       31 阅读