0
点赞
收藏
分享

微信扫一扫

力扣2156——查找给定哈希值的子串(哈希)

暮晨夜雪 2022-01-31 阅读 35

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

解题思路

用size()会报越界(因为是unsigned int,最好存下长度);
先求得最后一组的哈希值,然后倒序往前滑动窗口;
因为要求第一个,所以在逆序滑动的时候,需要遍历完,更新保留最新结果即是第一个
滑到的新的按 h a s h ∗ p o w e r + s [ 1 ] hash*power + s[1] hashpower+s[1] 加入,并减去划走的那个,也就是 s [ i + k ] ∗ p k s[i+k]*p^k s[i+k]pk,过程中要取模

代码

class Solution {
public:
    string subStrHash(string s, int power, int modulo, int k, int hashValue) {
        long long hash = 0, p = 1;
        int n = s.size(), res = n - k;
        for(int i = n - 1; i >= n - k; i--) {
            p = p * power % modulo;
            hash = (hash * power + s[i] - 'a' + 1) % modulo;
        }
        //hash %= modulo;
        for(int i = n - k - 1; i >= 0; i--) {
            hash = (hash * power % modulo + s[i] - 'a' + 1) - (s[i+k] - 'a' + 1) * p % modulo + modulo;
            hash %= modulo;
            if(hash == hashValue) res = i;
        }
        return s.substr(res, k);
    }
};
举报

相关推荐

0 条评论