1. 程式人生 > >1043. 輸出PATest(20)

1043. 輸出PATest(20)


【思路】先對比一下輸入字串和輸出字串。

(1)對於輸入的字串"edlesPayBestPATTopTeePHPereatitAPPT":

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int P_num=0,A_num=0,T_num=0,e_num=0,s_num=0,t_num=0;
	string str = "edlesPayBestPATTopTeePHPereatitAPPT";
	for(int i;i<str.length();i++)
	{
		char c = str[i];
		switch(c)
		{
			case 'P':
				P_num++;
				break;
			case 'A':
				A_num++;
				break;
			case 'T':
				T_num++;
				break;
			case 'e':
				e_num++;
				break;
			case 's':
				s_num++;
				break;
			case 't':
				t_num++;
				break;
		}
	}
	cout << "P:" << P_num << endl;
	cout << "A:" << A_num << endl;
	cout << "T:" << T_num << endl;
	cout << "e:" << e_num << endl;
	cout << "s:" << s_num << endl;
	cout << "t:" << t_num << endl;
	return 0;
}

執行結果為:

  (輸入的字串)                          (輸出的字串)

(2)對於輸出的字串"PATestPATestPTetPTePePee":(如上面右圖)

通過對照可發現規律為:當PATest各個字元個數均不為0時候按PATest順序輸出,然後對各個字元個數減1,當有字元個數為0時,將不為0的字元按對應順序輸出。直到PATest的所有字元個數都為0時候退出迴圈。

滿分的C++程式碼如下:

#include <iostream>
#include <string>
using namespace std;
int main()
{
	int P_num=0,A_num=0,T_num=0,e_num=0,s_num=0,t_num=0;
	string str;
	cin >> str;
	for(int i;i<str.length();i++)
	{
		char c = str[i];
		switch(c)
		{
			case 'P':
				P_num++;
				break;
			case 'A':
				A_num++;
				break;
			case 'T':
				T_num++;
				break;
			case 'e':
				e_num++;
				break;
			case 's':
				s_num++;
				break;
			case 't':
				t_num++;
				break;
		}
	}
	while(P_num!=0 || A_num!=0 || T_num!=0 || e_num!=0 || s_num!=0 || t_num!=0)
	{
		if(P_num != 0)
		{
			cout << "P";
			P_num--;
		}
		if(A_num != 0)
		{
			cout << "A";
			A_num--;
		}
		if(T_num != 0)
		{
			cout << "T";
			T_num--;
		}
		if(e_num != 0)
		{
			cout << "e";
			e_num--;
		}
		if(s_num != 0)
		{
			cout << "s";
			s_num--;
		}
		if(t_num != 0)
		{
			cout << "t";
			t_num--;
		}
	}
	return 0;
}