算法笔记(十五)查询字符串出现次数

题述:

给出N个字符串(由恰好三位大写字母组成),再给出M个查询字符串,问每个查询字符串在N个字符串中出现的次数。


代码:

#include <cstdio>

const int max=100;
char S[max][5], temp[5];
int hashTable[26*26*26+10];

//将字符串转化为整数
int hashFunc(char S[], int len)
{
int id=0;
for(int i=0; i<len; i++){
id=id*26 +(S[i]-'A');
}
return id;
}

int main()
{
    int n,m;
    scanf("%d%d", &n, &m);
    for(int j=0; j<n; j++)
{
scanf("%s", S[j]);
int id = hashFunc(S[j],3);    //将字符串S[i]转换为整数
hashTable[id]++;              //该字符串出现次数加1
}
for(int t=0; t<m; t++)
{
scanf("%s", temp);
int id = hashFunc(temp, 3);   //将字符串temp转换为整数
printf("%d\n", hashTable[id]);//输出该字符串出现的次数
}
return 0;

}



猜你喜欢

转载自blog.csdn.net/u014252478/article/details/80640334