题目:
输入M:接下来输入M个字符串
输入N:接下来输入N个字符串
求N个字符串分别在M个字符串中出现的次数
字符串均为小写字母组成 长度不超过4
要求:不准遍历,每次查找时间复杂度O(1)
分析:字符串hash初步 转换为n进制数(字符串字符种类个数为n),肯定能唯一表示
代码:
#include<iostream>
#include <string>
using namespace std;
int hashTable[26*26*26*26+10]={0};
int hashFunc(string s){
int id=0;
for(int i=0;i<s.length();i++){
id=id*26+s[i]-'a';//转转为26进制数 肯定唯一
}
return id;
}
int main(){
int M,N;
string s1[100];
string s;
cin>>M>>N;
for(int i=0;i<M;i++){
cin>>s1[i];
hashTable[hashFunc(s1[i])]++;
}
for(int i=0;i<N;i++){
cin>>s;
cout<<hashTable[hashFunc(s)]<<endl;
}
return 0;
}