本文为最近做过的一道编程笔试题,我自己实现的代码内容涉及较常用的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;
}
三、测试结果截图
有匹配测试结果:
无匹配测试结果: