给定一个长度不超过 10^4 的、仅由英文字母构成的字符串。请将字符重新调整顺序,按 PATestPATest… 这样的顺序输出,并忽略其它字符。当然,六种字符的个数不一定是一样多的,若某种字符已经输出完,则余下的字符仍按 PATest 的顺序打印,直到所有字符都被输出。
输入格式:
输入在一行中给出一个长度不超过 10^4的、仅由英文字母构成的非空字符串。
输出格式:
在一行中按题目要求输出排序后的字符串。题目保证输出非空。
输入样例:
redlesPayBestPATTopTeePHPereatitAPPT
输出样例:
PATestPATestPTetPTePePee
解题思路
先统计输入的字符串中P、A、T、e、s、t的个数,然后用一个StringBuilder按顺序把输出的字符串给链接起来,因为用Java做,这样会减少不少时间。
代码看着多,但是实际很简单。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int c[] = new int [6];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'P') c[0]++;
if (s.charAt(i) == 'A') c[1]++;
if (s.charAt(i) == 'T') c[2]++;
if (s.charAt(i) == 'e') c[3]++;
if (s.charAt(i) == 's') c[4]++;
if (s.charAt(i) == 't') c[5]++;
}
int max = 0; //字符数最多的数
for (int i = 0; i < c.length; i++){ // 判断最大值
if(c[i] > max)
max = c[i];
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i<max ; i++) {
if(c[0] != 0) {
sb.append('P');
c[0]--;
}
if(c[1] != 0) {
sb.append('A');
c[1]--;
}
if(c[2] != 0) {
sb.append('T');
c[2]--;
}
if(c[3] != 0) {
sb.append('e');
c[3]--;
}
if(c[4] != 0) {
sb.append('s');
c[4]--;
}
if(c[5] != 0) {
sb.append('t');
c[5]--;
}
}
System.out.println(sb);
}
}