题目:https://www.acwing.com/problem/content/140/
其实还算蛮简单的一个算法,但感觉能用到的地方也不少。
把字符串经行hash,并且可以再O(1)的时间复杂度查询其字串的hash值,不同字符串的hash值基本不会重合。
取字串s[l,r]hash值的方法:
hash[l,r]=f[r]-f[l-1]*p[r-l+1]。
比如
123456
abcdef
取def的hash值即f[def]
f[def]=f[abcdef]-f[abc]*p[3]
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; typedef unsigned long long ULL; char s[1000010]; int len,q; ULL f[1000010],p[1000010]; //定义为无符号型,可自动取模 int main() { scanf("%s",s+1); len=strlen(s+1); p[0]=1; for(int i=1;i<=len;i++) { f[i]=f[i-1]*131+(s[i]-'a'+1); //将字符串视作131进制的整数,f[i]为从头到i位的字符串的hash值 p[i]=p[i-1]*131; //p[i]=131^i } scanf("%d",&q); for(int i=1,l1,r1,l2,r2;i<=q;i++) { scanf("%d%d%d%d",&l1,&r1,&l2,&r2); if(f[r1]-f[l1-1]*p[r1-l1+1]==f[r2]-f[l2-1]*p[r2-l2+1]) puts("Yes"); else puts("No"); } return 0; }