字符串hash表示简介

字符串hash是指讲一个字符串s映射为一个整数,使得该整数可以尽可能唯一的代表字符串s。可以进行字符串的判断。

代码如下:

  1. #include<iostream>  
  2. #include<cstring>  
  3. int hashtable[26*26*26+10];  
  4. using namespace std;  
  5. int translate(string s){  
  6.     int sum=0;  
  7.     int len=s.length();  
  8.     for(int i=0;i<len;i++){    
  9.         if(s[i]>='A'&&s[i]<='Z')      
  10.             sum=sum*26+(s[i]-'A');  
  11.         if(s[i]>='a'&&s[i]<='z')  
  12.             sum=sum*26+(s[i]-'a');  
  13.     }  
  14.     return sum;  
  15. }  
  16. int main(){  
  17.     int n,m;  
  18.     cin>>n>>m;  
  19.     for(int i=0;i<n;i++){  
  20.         string s;  
  21.         cin>>s;  
  22.         int temp=translate(s);  
  23.         hashtable[temp]++;  
  24.     }  
  25.     for(int i=0;i<m;i++){  
  26.         string s;  
  27.         cin>>s;  
  28.         int temp=translate(s);  
  29.         cout<<hashtable[temp]<<endl;  
  30.     }  
  31.     return 0;  
  32. }  

猜你喜欢

转载自blog.csdn.net/qq_36926514/article/details/79433129