题目要求:写出一个函数,查找出每个字符出现的次数,主要区分大小写,要求时间复杂度是O(n)。
分析:用256个元素的数组count,来分别记录ASCII码为0~255的字符的个数,初始化为0,遍历每个字符,对该字符对应的数组元素的值加1。最后count[ i ]中存储的数值就是字符 i 出现的次数。
具体实现如下:
#include <iostream>
int main(int argc, const char * argv[]) {
int count[256] = {0};
char str[] = "I am a student!";
for (int i = 0; str[i] != '\0'; i++)
count[str[i]]++;
for (int i = 0; i < 256; i++)
{
if (count[i] > 0)
printf("字符 %c 出现了 %d 次\n", i, count[i]);
}
return 0;
}