码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-09-13 21:20:04      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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

输入:字符串(英文字母),长度不超过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\n%d\n", (max_index+a), count[max_index]);
    
    return 0;
}

 

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

标签:

原文地址:http://www.cnblogs.com/Cmfvacks-IsLjj/p/4805555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!