首页 > 其他 > 详细

字符串Hash

时间:2019-04-15 13:26:20      阅读:102      评论:0      收藏:0      [点我收藏+]

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;
}

字符串Hash

原文:https://www.cnblogs.com/Agnel-Cynthia/p/10710080.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!