一.问题描述
给定一个长度不超过10000的、仅由英文字母构成的字符串。请将字符重新调整顺序,按GPLTGPLT…这样的顺序输出,并忽略其它字符。当然,四种字符(不区分大小写)的个数不一定是一样多的,若某种字符已经输出完,则余下的字符仍按GPLT的顺序打印,直到所有字符都被输出。
输入格式:
输入在一行中给出一个长度不超过10000的、仅由英文字母构成的非空字符串。
输出格式:
在一行中按题目要求输出排序后的字符串。题目保证输出非空。
输入样例:
pcTclnGloRgLrtLhgljkLhGFauPewSKgt输出样例:
GPLTGPLTGLTGLGLL
二.问题分析
1)看到这个题先来理解一下题意,题目中给出了一串英文(不区分大小写)的字符串,然后让你找到GPLT四个字符按GPLT的顺序输出字符,如果对应字符个数不够了则直接输出下一个字符,直到全部输出为止。
2)首先我们就要计算gplt这四个字符各自的数目,并且存储起来。这里我使用了 unordered_map
这一存储结构进行计数。
3)得到它们各自的个数后按顺序输出即可,见下面代码。
三.C++代码
–> 代码
#include<iostream>
#include<string>
#include<unordered_map>
#include<cstdlib>
using namespace std;
int main()
{
string s;
cin>>s;
unordered_map<char,int>map;
//初始化四个字符
map.emplace('G',0);
map.emplace('P',0);
map.emplace('L',0);
map.emplace('T',0);
//进行计数
for(int i=0;i<s.size();i++)
{
//如果是小写字母记得减32转换为大写字母
if(s[i]=='p' || s[i]=='g' || s[i]=='l' || s[i]=='t')
{
map[s[i]-32]++;
}
if(s[i]=='P' || s[i]=='G' || s[i]=='L' || s[i]=='T')
{
map[s[i]]++;
}
}
//遍历个数,自己进行个数查找判断正误
// for(auto iter=map.begin();iter!=map.end();iter++)
// {
// cout<<iter->first<<" "<<iter->second<<endl;
// }
//输出标准顺序
while(map['G']!=0 || map['P']!=0 || map['L']!=0 || map['T']!=0)
{
if(map['G']) {cout<<'G';map['G']--;}
if(map['P']) {cout<<'P';map['P']--;}
if(map['L']) {cout<<'L';map['L']--;}
if(map['T']) {cout<<'T';map['T']--;}
}
cout<<endl;
system("pause");
return 0;
}
–> 结果: