写在前面
测试用例
input:
redlesPayBestPATTopTeePHPereatitAPPT
output:
PATestPATestPTetPTePePee
ac代码
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 10010;
char str[maxn], dict[6] = {'P','A','T','e','s','t'};
int hashTable[6] = {0};int main()
{scanf("%s", str);int len = strlen(str), sum=0;for(int i=0; i< len; i++){for(int j=0; j<6; j++){if(str[i] == dict[j]){hashTable[j]++;sum++;}}}while(sum > 0){for(int i=0; i<6; i++){if(hashTable[i]>0){printf("%c", dict[i]);hashTable[i]--;sum--;}}}return 0;
}
- 个人改造版
- 数组存储字符出现次数,下标为字符ascii码
- 目标字符(6个)hash表初始化为1(hashTable方便全部初始化为0)
- 打印输出个数大于1,消除初始化的次数1。灵活思考点
#include <iostream>
#include <cstring>
using namespace std;const int maxn = 10010;
char str[maxn], dict[6] = {'P','A','T','e','s','t'};
int hashTable[256] = {0};
int main()
{hashTable['P'] = hashTable['A'] = hashTable['T'] = 1;hashTable['e'] = hashTable['s'] = hashTable['t'] = 1;scanf("%s", str);int len = strlen(str), sum=0;for(int i=0; i< len; i++)if(hashTable[str[i]]>0){hashTable[str[i]]++;sum++;}while(sum > 0){for(int i=0; i<6; i++)if(hashTable[dict[i]]>1){printf("%c", dict[i]);hashTable[dict[i]]--;sum--;}}return 0;
}
学习代码
- 1043. 输出PATest(20).cpp···推荐···
- 整型数组记录字符出现次数,下标为字符对应ascii值
- 逐个读入字符,结束符ch!=EOF
- 循环打印次数不为0字符并动态更新剩余打印次数
#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;
}