一道关于字符查找的笔试题
给你一个由小写字母组成的字符串,找出字符串中出现次数最多的字母,如果出现次数最多的字母有多个,输出最小的那个。
例如:
str = "abcd", 输出 a
str = "bbaa", 输出 a
str = "jsdhfjkshdfjksahdfjkhsaj" 输出 j
#include <stdio.h>
#include <string.h>
#define MAX_CH 26
char GetChMostTime(char *pSrc)
{
if (NULL == pSrc){
return -1;
}
int len = strlen(pSrc);
int count[MAX_CH] = { 0 };
char *pTem = pSrc;
int index = 0, i = 0, max = 0, result =0;
for ( i = 0; i < len; i++)
{
if (pTem[i] >= 'a' && pTem[i]<= 'z')
{
index = pTem[i] - 'a'; //取出小写字母减'a',得到索引范围为0-25,即上面定义的数组长度26
count[index]++;
}
}
for (i = 0, max = count[0]; i < MAX_CH; i++)
{
if (max<count[i])
{
max = count[i];
result = i;
}
}
return ('a' + result);
}
int main()
{
char *str1 = "abcd";
printf(" str1 = \"abcd\": %c\n", GetChMostTime(str1));
char *str2 = "bbaa";
printf("str2 = \"bbaa\": %c\n", GetChMostTime(str2));
char *str3 = "jsdhfjkshdfjksahdfjkhsaj";
printf("str3 = \"jsdhfjkshdfjksahdfjkhsaj\": %c\n", GetChMostTime(str3));
return 0;
}
运行结果: