题目:
请编写程序,找出一段给定文字中出现最频繁的那个英文字母。
输入格式:
输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。
输出格式:
在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。
输入样例:
This is a simple TEST. There ARE numbers and other symbols 1&2&3…
输出样例:
e 7
分析与总结:
- 思路: 首先将输入字符串中的大写字母转换为小写字母,再将字符串个字符按ASCII码降序排序,然后从前往后遍历字符串,统计出现频率最高的字母。
- 总结:由于有空格,不能用scanf输入字符,可用getchar 函数;题目要统计的是频率最高的字母,不是字符串中的任意字符,统计时应判断该字符是否是字母;要注意输入有多个字符但仅有一个字母的情况;要输出字母序最小的那个字母。
程序:
#include <stdio.h>
#include <string.h>
typedef struct{
char c;
int cnt;
}Character;
void Shellsort(char En[], int N);
int main()
{
char En[1001];
Character C, Max;
int i, j;
char c;
for(i = 0; (c = getchar()) != '\n'; i++){
En[i] = c;
}
En[i] = '\0';
for(i = 0; En[i] != '\0'; i++){
if(En[i] >= 'A' && En[i] <= 'Z'){
En[i] = En[i] + 'a' - 'A';
}
}
Shellsort(En, strlen(En));
C.cnt = 1;
for(i= 0; i < strlen(En) && (En[i] <= 'a' || En[i] >= 'z'); i++){}
Max.c = En[i];
Max.cnt = 1;
for(i = i; i < strlen(En); i++){
if(En[i] >= 'a' && En[i] <= 'z'){
C.c = En[i];
if(En[i-1] == En[i] ){
while(En[i-1] == En[i]){
C.cnt++;
i++;
}
}
}
if(Max.cnt <= C.cnt){
Max = C;
}
C.cnt = 1;
}
printf("%c %d", Max.c, Max.cnt);
return 0;
}
void Shellsort(char En[], int N)
{
int i, j,Increament;
char tmp;
for(Increament = N/2; Increament > 0; Increament /= 2){
for(i = Increament; i < N; i++){
tmp = En[i];
for(j = i; j >= Increament; j -= Increament){
if(tmp > En[j-Increament]){
En[j] = En[j-Increament];
}
else
break;
}
En[j] = tmp;
}
}
}