PAT Basic 1043 输出PATest (20分)

题目

给定⼀个⻓度不超过10000的、仅由英⽂字⺟构成的字符串。请将字符重新调整顺序,按“PATestPATest….”这样的顺序输出,并忽略其它字符。当然,六种字符的个数不⼀定是⼀样多的,若某种字符已经输出完,则余下的字符仍按PATest的顺序打印,直到所有字符都被输出。
输⼊格式:
输⼊在⼀⾏中给出⼀个⻓度不超过10000的、仅由英⽂字⺟构成的⾮空字符串。
输出格式:
在⼀⾏中按题⽬要求输出排序后的字符串。题⽬保证输出⾮空。
输⼊样例:
redlesPayBestPATTopTeePHPereatitAPPT
输出样例:
PATestPATestPTetPTePePee

题目分析

  1. 散列统计PATest每二个字母出现次数,记录在unordered_map中
  2. 循环打印PATest(若字母存在次数-1并打印,若字母不存在不打印)
  3. 使用标记,记录是否PATest出现次数都已为0,退出循环

code

code 01


#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main(int argc, char * argv[]) {
    string s;
    getline(cin,s);
    unordered_map<char, int> m;
    for(int i=0; i<s.length(); i++) {
        m[s[i]]++;
    }
    bool flag = true;
    while(flag) {
        flag = false;
        if(m['P']-->0)printf("P"),flag=true;
        if(m['A']-->0)printf("A"),flag=true;
        if(m['T']-->0)printf("T"),flag=true;
        if(m['e']-->0)printf("e"),flag=true;
        if(m['s']-->0)printf("s"),flag=true;
        if(m['t']-->0)printf("t"),flag=true;
    }
    return 0;
}

code 02

#include <iostream>
using namespace std;
int main() {
    int map[128] = {0}, c;
    while ((c = cin.get()) != EOF) map[c]++;
    while (map['P'] > 0 || map['A'] > 0 || map['T'] > 0 || map['e'] > 0 ||
            map['s'] > 0 || map['t'] > 0) {
        if (map['P']-- > 0) cout << 'P';
        if (map['A']-- > 0) cout << 'A';
        if (map['T']-- > 0) cout << 'T';
        if (map['e']-- > 0) cout << 'e';
        if (map['s']-- > 0) cout << 's';
        if (map['t']-- > 0) cout << 't';
    }
    return 0;
}


猜你喜欢

转载自www.cnblogs.com/houzm/p/12237665.html