字符串把不同的字符映射成哈希
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]