字符串哈希

字符串把不同的字符映射成哈希
2223. 构造字符串的总得分和

模板:

long[] p;
    long[] h;
    int P=13131;
    public long sumScores(String s) {
        int n=s.length();
        p=new long[n+1];
        h=new long[n+1];
        p[0]=1;
        h[0]=0;
        for (int i = 1; i <= n; i++) {
            p[i]=p[i-1]*P;
            h[i]=s.charAt(i-1)+h[i-1]*P;
        }
       
    }
    public long get(int l ,int r){
        return h[r]-h[l-1]*p[r-l+1];
    }

原理:字符串前缀和

h[i]=h[i-1]*P+s[i]
A, h[1]=A
AB,h[2]=A*P1+B
ABC,h[3]=(A*P1+B)*P+C=A*P2+B*P+C

区间和:DE=ABCDE-ABC=h[r]-h[l]*p[r-l+1]=h[5]-h[3]*p[3]

解法来自b站:董晓算法

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值