实现一个函数,输入为一个字符串只包含a-z,返回字符串中出现次数最多的字符及其出现次数,如果有出现同样次数的,则返回在字符串中位置更靠前的
#include <stdio.h>
int get_max_apperance(const char *str, char *most_apperance_char, int *max_times);
int main()
{
/* Write C code in this online editor and run it. */
printf("请输入字符串只包含a-z\n");
char str[1024]={0};
char c;
int times;
int ret ;
//scanf("%s", &str);
printf("str=%s\n", str);
ret = get_max_apperance(str, &c, ×);
printf("执行结果:%s\n", ret==1?"失败":"成功");
if(0 == ret){
printf("字符串%s中出现次数最多的字符:%c\n出现次数%d\n", str, c, times);
}
return 0;
}
/*start time 202301291521*/
/*实现一个函数,输入为一个字符串只包含a-z,返回字符串中出现次数最多的字符及其出现次数,如果有出现同样次数的,则返回在字符串中位置更靠前的*/
/*入参:str 字符串
出参:char 出现次数最多的字符
times 出现次数
返回值:0 代表成功
1 代表失败(比如字符串为空、出现了超出范围a-z的字符)
*/
int get_max_apperance(const char *str, char *most_apperance_char, int *max_times){
int ret = 0;
struct time_counter{
int times;//出现次数
int first_pos;//第一次出现位置
};
struct time_counter counter_arr[26]={0};
char c;
int times;
int i;
int max_apperance_index;
if(NULL == str){
return 1;//字符串为空
}
//初始化
for(i=0;i<26;i++){
counter_arr[i].times = 0;
counter_arr[i].first_pos = -1;
}
for(i=0;str[i]!='\0';i++){
c = str[i] - 'a';
if(c < 0 || c > 25){
return 1;//超过范围
}
counter_arr[c].times++;
if(-1 == counter_arr[c].first_pos){
counter_arr[c].first_pos = i;
}
}
max_apperance_index=0;
for(i=0;i<26;i++){
if(counter_arr[max_apperance_index].times < counter_arr[i].times){
max_apperance_index = i;
}
if(counter_arr[max_apperance_index].times == counter_arr[i].times && counter_arr[max_apperance_index].first_pos > counter_arr[i].first_pos){
max_apperance_index = i;
}
}
*most_apperance_char = max_apperance_index + 'a';
*max_times = counter_arr[max_apperance_index].times;
return 0;
};
//end coding time 202301291539
//end testing time 202301291607
标签:题目,int,max,times,char,apperance,str,字符串,排序
From: https://www.cnblogs.com/studentWangqy/p/17073060.html