Java + 字符串 Hash 算法模板

Java + 字符串 Hash 算法模板

public class StringHash {
    char[] str;
    long seed = 31;
    long mod = 1_000_000_007;

    int n;
    // hash前缀和
    long[] pre;
    // p的幂次
    long[] pow;

    StringHash(String s, int seed, long mod) {
        this.str = s.toCharArray();
        this.seed = seed;
        this.mod = mod;

        preHash();
    }

    private void preHash() {
        this.n = this.str.length;
        pre = new long[n + 1];
        pow = new long[n + 1];

        pow[0] = 1;
        for (int i = 1; i <= n; i++) {
            pow[i] = pow[i - 1] * seed % mod;
        }
        for (int i = 0; i < str.length; i++) {
            pre[i + 1] = (pre[i] * seed % mod + str[i]) % mod;
        }
    }

    StringHash(String s) {
        this.str = s.toCharArray();

        preHash();
    }

    public long query(int l, int r) {
        long res = pre[r + 1] - pre[l] * pow[r - l + 1] % mod;
        return (res % mod + mod) % mod;
    }

    public long rotate(int l) {
        if (l < 0 || l >= str.length - 1) {
            return query(0, str.length - 1);
        } else {
            long h1 = query(0, l);
            long h2 = query(l + 1, str.length - 1);
            return (h2 * pow[l + 1] % mod + h1) % mod;
        }
    }

    public long evaluate(String s) {
        long h = 0;
        for (char c: s.toCharArray()) {
            h = (h * this.seed % this.mod + c) % mod;
        }
        return h;
    }
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值