1043 输出PATest (20 分)
给定一个长度不超过 104 的、仅由英文字母构成的字符串。请将字符重新调整顺序,按 PATestPATest....
这样的顺序输出,并忽略其它字符。当然,六种字符的个数不一定是一样多的,若某种字符已经输出完,则余下的字符仍按 PATest 的顺序打印,直到所有字符都被输出。
输入在一行中给出一个长度不超过 104 的、仅由英文字母构成的非空字符串。
在一行中按题目要求输出排序后的字符串。题目保证输出非空。
redlesPayBestPATTopTeePHPereatitAPPT
PATestPATestPTetPTePePee
【我的代码】
// 1043 输出PATest (20 分).cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
//输入
string a;
int aa[6] = { 0 };
int count = 0;
getline(cin, a);
int i = 0;
for (; i < a.length(); i++) {
if (a[i] == 'P') {
aa[0]++;
count++;
}
else if (a[i] == 'A') {
count++;
aa[1]++;
}
else if (a[i] == 'T') {
count++;
aa[2]++;
}
else if (a[i] == 'e') {
aa[3]++;
count++;
}
else if (a[i] == 's') {
aa[4]++;
count++;
}
else if (a[i] == 't') {
aa[5]++;
count++;
}
}
//处理
int j = 0;
for (; count != 0;) {
if (aa[j] != 0) {
if (j == 0)
cout << "P";
if (j == 1)
cout << "A";
if (j == 2)
cout << "T";
if (j == 3)
cout << "e";
if (j == 4)
cout << "s";
if (j == 5)
cout << "t";
aa[j]--;
count--;
}
if (j == 5)
j = 0;
else
j++;
}
}
【网上代码】
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int mapp[128] ={0},c;
while((c=cin.get())!=EOF) mapp[c]++;
while(mapp['P']>0||mapp['A']>0||mapp['T']>0||mapp['e']>0||mapp['s']>0||mapp['t']>0){
if(mapp['P']-->0) cout<<'P';
if(mapp['A']-->0) cout<<'A';
if(mapp['T']-->0) cout<<'T';
if(mapp['e']-->0) cout<<'e';
if(mapp['s']-->0) cout<<'s';
if(mapp['t']-->0) cout<<'t';
}
return 0;
}
【思路】
转化为数组处理就会发现所有条件均可满足,可能没有处理好,代码有点冗余,不过已经是最快时间完成的了。
对比了一下别人的代码,看到有一个稍短一点的,同样也是使用数组完成的,但是他这样做法会浪费很多空间,实际上使用的空间为仅有6个int,然而申请了128个int,ummm,有利有弊。