忘了从哪儿看到的题了....输入一个字符串,按字母出现次数从大到小输出(不考虑其他非字母字符),相同次数的按输入顺序输出。 例:输入aaccnfbbeeee123 输出 e:4 a:2 c:2 b:2 n:1 f:1
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct ST
{
char c;
int n;
};
int main()
{
string str, str1; cin >> str; vector<ST> V;
//去除重复的字母,不改变顺序 得str1
int nlwr[26] = { 0 }; int nupr[26] = { 0 };
for (int i = 0; i < str.size(); i++)
{
if (islower(str[i]))
{
nlwr[str[i] - 'a'] += 1; //如果str[i]是a 则nlwr[0]+1,是b则nlwr[1]+1,c则nlwr[2]+1...
if (nlwr[str[i] - 'a'] == 1)
str1.push_back(str[i]);
}
if (isupper(str[i]))
{
nupr[str[i] - 'A'] += 1;
if (nupr[str[i] - 'A'] == 1)
str1.push_back(str[i]);
}
}
//cout << str1 << endl;
//这个按输入顺序真的是有点.. 用map它会自己排升序,对次数相同的多个字母很可能会与输入顺序不一致,所以用了结构体vector按顺序压入
for (int i = 0; i < str1.size(); i++)
{
ST st;
st.c = str1[i];
st.n = count(str.begin(), str.end(), str1[i]);
V.push_back(st);
//cout << st.c << ' ' << st.n << endl;
}
//字符出现的次数最大是串长,从大到小比对ST中的n,有就输出n和相应的c
for (int i = str.size(); i > 0; i--)
{
for (auto itr = V.begin(); itr != V.end(); ++itr)
if ((*itr).n == i)
cout << (*itr).c << " : " << (*itr).n << endl;
}
return 0;
}

京公网安备 11010502036488号