字符串Hash

Hash——字符串匹配(求s1在s2中出现的次数)

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
typedef unsigned long long ull;
ull base=131;
ull po[100010],hs[100010*100];
char s1[100010],s2[100010*100];
int n,ans=1,T;
//Hash处理(l,r)的字符串的hash值
ull geth(int l,int r)
{
    return (ull)hs[r]-po[r-l+1]*hs[l-1];
}
main()
{
   // freopen("oulipo.in","r",stdin);
   // freopen("oulipo.out","w",stdout);
    po[0]=1;
    //预处理hash值
    for (int i=1; i<=10010-5; i++)
        po[i]=po[i-1]*base , cout << po[i] << endl;

    scanf("%d",&T);
    while(T--)
    {
        scanf("%s%s",s1+1,s2+1);
        int l1=strlen(s1+1),l2=strlen(s2+1);
        ull a1=0,ans=0;
        for (int i=1; i<=l1; i++)
            a1=a1*base+(ull)s1[i];
        for (int i=1; i<=l2; i++)
            hs[i]=hs[i-1]*base+s2[i];
        for (int i=1; i+l1-1<=l2; i++)
            //截取相同长度,hash求值
            if (a1==geth(i,i+l1-1))
                ans++;
        printf("%d\n",ans);
    }
}

 

用unique

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
ull base = 131;
ull H[30010];
char s[1005];
int n, ans = 1;

ull hashs(char s[])
{
    int len = strlen(s);
    ull ans = 0;
    for (int i = 0; i<len; i++)
        ans = ans*base + (ull)s[i];
    return ans & 0x7fffffff;
}

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%s", s);
        H[i] = hashs(s);
    }
    sort(H + 1, H + n + 1);
    printf("%d\n", (int)(unique(H + 1, H + n + 1) - H - 1));
    return 0;
}

转载于:https://www.cnblogs.com/Agnel-Cynthia/p/10710080.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值