题解 | #字符统计#

字符统计

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

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
如果compar返回值小于0(< 0),那么p1所指向元素会被排在p2所指向元素的左面;
如果compar返回值等于0(= 0),那么p1所指向元素与p2所指向元素的顺序不确定;
如果compar返回值大于0(> 0),那么p1所指向元素会被排在p2所指向元素的右面。
*/
typedef struct {
    int id;
    int _count;
} Data;

int compar(const void *p1, const void *p2){
    Data* a = (Data*)p1;
    Data* b = (Data*)p2;
    if(a->_count>b->_count){
        return -1;
    }
    else if(a->_count<b->_count){
        return 1;
    }
    else{
        if(a->id>b->id)
        {
            return 1;
        }
        else {
            return -1;
        }
    }
}

int main() {
    char str[1000] = "";
    Data count[128];
    scanf("%s",str);
    int len = strlen(str);
    for(int i=0;i<128;i++)
    {
        count[i].id = i;
        count[i]._count=0;
    }
    for(int i=0;i<len;i++){
        count[str[i]].id = str[i];
        count[str[i]]._count++;
    }
    qsort(count,128,sizeof(Data),compar);
    for(int i=0;i<128;i++)
    {
        if(count[i]._count>0)
        {
            printf("%c",count[i].id);
        }
    }
    return 0;
}

全部评论

相关推荐

求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
SHC2:关键问题是你这三段实习是三个不同的岗位…你这样子秋招就是只有一段实习的本科生..
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务