字符串哈希和哈希表

字符串哈希

#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
using namespace std;
typedef unsigned long long ull;

int n;
char str[1510];
set<ull> S;

ull str_hash(char str[])                    //2^64自然溢出 
{
    int base=131, len=strlen(str);
    ull ans=0;
    for(int i=0; i<len; i++)
        ans=ans*base+ull(str[i]-'a'+1);     //或 ans=ans*base+ull(str[i]) 直接使用ASCII码 
    return ans;
}

int main()
{
    scanf("%d", &n);
    for(int i=1; i<=n; i++) scanf("%s", str), S.insert(str_hash(str));
    printf("%d\n", S.size());               //统计方法还可以将全部哈希值顺序存储到一个数组中,排序后计算不重复值 
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lfyzoi/p/10818640.html