20150912华为机考1之"输入一个字符串,将其中出现次数最多的字符输出"

不吐槽华为的服务器了,直接上正文

输入:字符串(英文字母),长度不超过128

输出:出现频率最高的字母

思路写在注释文档

/*  Input a string
 *  Output the most frequent character
 *
 *  The way of thinking:
 *  using ASCII, count the number of each character
 *  then find out the max number(max_num)
 *  and its according index(max_index)
 *  so the most frequent character is (index + 'a')
 *
 *  time_complexity:O(n)?
 */
#include <stdio.h>
#include <string.h>

int main(){
    char s[128]={0};
    int count[26]={0};
    int len=0, i=0;
    int max_num, max_index;
    
    scanf("%s", s);
    len = (int)strlen(s);
    for(i=0; i<len; i++)
        count[(s[i]-'a')] += 1;
    
    max_num=count[0];
    max_index=0;
    for(i=1; i<26; i++){
        if(count[i] > max_num){
            max_num = count[i];
            max_index = i;
        }
    }
    
    printf("%c
%d
", (max_index+'a'), count[max_index]);
    
    return 0;
}
原文地址:https://www.cnblogs.com/Cmfvacks-IsLjj/p/4805555.html