字符统计及重排

标题:字符统计及重排 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
给出一个仅包含字母的字符串,不包含空格,统计字符串中各个字母(区分大小写)出现的次数,并按照字母出现次数从大到小的顺序输出各个字母及其出现次数。如果次数相同,按照自然顺序进行排序,且小写字母在大写字母之前。

#include <bits/stdc++.h>

using namespace std;

typedef struct{
    char ch;
    int value;
}node;


int s1[26],s2[26];


bool cmp(node a,node b) {
    if(a.value == b.value) {
        if(islower(a.ch) && islower(b.ch)) {
            return a.ch < b.ch;
        }
        if(isupper(a.ch) && isupper(b.ch)) {
            return a.ch < b.ch;
        }
        if(islower(a.ch)) {
            return true;
        } else {
            return false;
        }
    }
    return a.value > b.value;
}

int main(void)
{
    string str;
    while(cin >> str) {
        memset(s1,0,26 * sizeof(int));
        memset(s1,0,26 * sizeof(int));
        for(int i=0;i<(int)str.size();i++) {
            if(islower(str[i])) {
                s1[str[i] - 'a'] += 1;
            } else {
                s2[str[i] - 'A'] += 1;
            }
        }
        vector<node> ans;
        for(int i=0;i<26;i++) {
            if(s1[i] != 0) {
                node t;
                t.ch = i + 'a';
                t.value = s1[i];
                ans.push_back(t);
            }
            if(s2[i] != 0) {
                node t;
                t.ch = i + 'A';
                t.value = s2[i];
                ans.push_back(t);
            }
        }
        sort(ans.begin(),ans.end(),cmp);
        for(int i=0;i<ans.size();i++) {
            cout << ans[i].ch << ":" << ans[i].value << ';';
        }
    }
    return 0;
}


全部评论
import sys while True:     try:         s=list(sys.stdin.readline().strip())         sets=set(s)         dicts={}         for i in sets:             if i.isupper():                 dicts[i]=[s.count(i),s.index(i),1]             else:                 dicts[i]=[s.count(i),s.index(i),-1]         print(dicts)         dicts=sorted(dicts.items(),key=lambda x:(-x[1][0],x[1][2],x[1][1]))         res=[]         for i in range(len(dicts)):             temp=[dicts[i][0],dicts[i][1][0]]             res.append(':&(31936)#39;.join(str(i) for i in temp))         print(';&(31937)#39;.join(res))     except:         break 这么搞不知道对不对,次数第一,同是小写和同是大写看先后顺序,大写在小写后,XXxyxy排出来是x:2;y:2;X:2
点赞 回复 分享
发布于 2022-10-05 22:38 江苏
不太理解题目里的又要自然顺序,又要小写在大写之前,如果我大写先出现怎么办呢,两个只能满足一个
点赞 回复 分享
发布于 2022-10-05 22:22 江苏

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务