题解 | #计算某字母出现次数#
计算某字母出现次数
http://www.nowcoder.com/practice/a35ce98431874e3a820dbe4b2d0508b1
#include <iostream> #include <cstring> using namespace std; #define maxSize 1000 int fun() { // 用一个int数组 哈希统计 数字(0~9)和字母(大、小写)的出现次数,忽略空格 // 查找时,数字和字母不会发生哈希冲突,因为数字的ASCII码最大值为57(9,十进制),字母的ASCII码最小值为65(A,十进制)。 char str[maxSize] = {'\0'}; int HashTable[500] = {0}; cin.getline(str, maxSize); for(int i = 0; i < strlen(str); i++) { if(str[i] != ' ') { ++ HashTable[(int)str[i]]; } } char targetElem; cin >> targetElem; if(targetElem >= 'a' && targetElem <= 'z') return HashTable[(int)targetElem] + HashTable[(int)(targetElem - 32)]; else return HashTable[(int)targetElem] + HashTable[(int)(targetElem + 32)]; } int main() { int ans = fun(); cout << ans << endl; return 0; }