题解 | #HJ102 字符统计#

字符统计

http://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

C语言版本

#include <stdio.h>
#include <string.h>

int main() {
    char string[1001];
    scanf("%s", string);
    int length = strlen(string);
    int hist_c[36] = {0};
    for (int i = 0; i < length; i++) {
        if (('0' <= string[i]) && (string[i] <= '9')) {
            hist_c[string[i]-'0'] += 1;
        } else if (('a' <= string[i]) && (string[i] <= 'z')) {
            hist_c[10 + string[i]-'a'] += 1;
        }
    }
    int count = 0;
    for (int i = 0; i < 36; i ++) {
        if (hist_c[i]>0) {
            count += 1;
        }
    }
    char c[37] = "0123456789abcdefghijklmnopqrstuvwxyz";
    for (int i = 0; i < 36; i++) {
        for (int j = i+1; j < 36; j++) {
            if ((hist_c[i] < hist_c[j]) || ((hist_c[i] == hist_c[j]) && (c[i] > c[j]))) {
                int ti;
                char tc;
                ti = hist_c[i];
                hist_c[i] = hist_c[j];
                hist_c[j] = ti;
                tc = c[i];
                c[i] = c[j];
                c[j] = tc;
            }
        }
    }
    c[count] = '\0';
    printf("%s\n", c);
    return 0;
}

Python版本

while True:
    try:
        string = input()
        c_set = set([c for c in string])
        c_hist = [(c, string.count(c)) for c in c_set]
        c_hist.sort(key=lambda x: (-x[1], x[0]))
        out = ''.join([x[0] for x in c_hist])
        print(out)
    except Exception:
        break

这时候不得不感慨,“人生苦短,我用 Python”。

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:21
点赞 评论 收藏
分享
宇智波爱学习:我还没收到笔试
投递荣耀等公司10个岗位
点赞 评论 收藏
分享
尊尼获获:闺蜜在哪?
点赞 评论 收藏
分享
评论
3
2
分享
牛客网
牛客企业服务