• 字符串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
    ",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
    ", (int)(unique(H + 1, H + n + 1) - H - 1));
        return 0;
    }

  • 相关阅读:
    C++扬帆远航——4(百钱百鸡)
    C++扬帆远航——3(打印图形)
    C++扬帆远航——2
    web开发之Servlet 三
    web开发之Servlet 二
    web开发之Servlet 一
    迟来的2017年计划
    JSP 学习二
    JSP 学习一
    window7 32位安装Oracle11g
  • 原文地址:https://www.cnblogs.com/Agnel-Cynthia/p/10710080.html
Copyright © 2020-2023  润新知