C++查找字符串中各子串出现的次数并按出现次序逆序排序输出

本文为最近做过的一道编程笔试题,我自己实现的代码内容涉及较常用的vector的结构体排序、字符串子串或子字符的位置查找等。代码实现方式多种多样,此处本人提供的代码可以获得正确解,仅供大家参考。

一、题目描述

给出一个由大写字母A~Z组成的字符串,找出其中出现3到5次的字符,按字母逆序打印出来,如果没有找到,打印字符no。

输入描述:
A~Z组成的字符串
输出描述:
出现3到5次的字符,按字母逆序打印出来,如果没有找到,打印字符no

示例:
输入: DACUDEAONER
输出: no

二、C++实现代码程序

#include<iostream>
#include<vector>
#include <algorithm>

using namespace std;

struct Node {
    char str;
    int index = 0;
};

bool GreaterSort(Node a, Node b) { return (a.index > b.index); }

int main() {
    string str;
    cin >> str;
    int count[26] = { 0 };
    for (int i = 0; i < str.length(); ++i) {
        int number = str[i] - 'A';
        count[number] += 1;
    }
    vector<Node> result;
    for (int i = 0; i < 26; ++i) {
        if (count[i] > 2 && count[i] < 6) {
            Node node;
            node.str = 'A' + i;
            int n = str.find(node.str);
            if ((n = str.find(node.str)) != string::npos) {
                node.index = n;
            }
            result.push_back(node);
        }
    }
    sort(result.begin(), result.end(), GreaterSort);
    if (result.size() > 0) {
        for (Node n : result) {
            cout << n.str;
        }
        cout << endl;
    }
    else {
        cout << "no" << endl;
    }
    return 0;
}

三、测试结果截图

有匹配测试结果:
测试结果1

无匹配测试结果:
测试结果2

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值