算法介绍
想要比较两个字符串是否相等需要逐位判断。哈希的思想就是将字符串映射成数字再比较。
正确性证明
对于一个字符串 ,想要映射成数字 。可以用进制的方法将 变为数字 ,即 为 进制下的 。通常, 需要取一个大于字符种数的质数,常取 。
然而 最终的值远远不是整数类型结构可以储存的,必须对这个数进行取模。常用模数 ,可以使用 unsigned long long 类型自然溢出实现。
这样就实现了哈希。
代码实现
#include<bits/stdc++.h>
using namespace std;
const int P=131;
unsigned long long _hash(string s){
unsigned long long res=0;
for(auto ch:s)
res=res*P+ch;
return res;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
int n;cin>>n;
set<unsigned long long>st;
for(int i=1;i<=n;++i){
string s;cin>>s;
st.insert(_hash(s));
}
cout<<st.size()<<"\n";
return 0;
}拓展
当然,哈希存在冲突,即两个不同的字符串的哈希值相等。但是除非刻意构造,哈希冲突的概率很小。
那如果存在了冲突呢?不难想到可以用 和 两个进制进行计算,如果两个字符串的两个哈希值都分别相等,则两个字符串相同。当然你也可以更换模数,但是这样写有点麻烦。
这样做大大减小了哈希冲突的概率,基本不会被卡。
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
const int P1=131,P2=137;
pair<ull,ull>_hash(string s){
ull res1=0,res2=0;
for(auto ch:s){
res1=res1*P1+ch;
res2=res2*P2+ch;
}
return make_pair(res1,res2);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr),cout.tie(nullptr);
int n;cin>>n;
set<pair<ull,ull>>st;
for(int i=1;i<=n;++i){
string s;cin>>s;
st.insert(_hash(s));
}
cout<<st.size()<<"\n";
return 0;
}