字符串哈希算法


題目: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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM