答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于 PAT 的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。
得到“答案正确”的条件是:
字符串中必须仅有 P、 A、 T这三种字符,不可以包含其它字符;
任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串;
如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a、 b、 c 均或者是空字符串,或者是仅由字母 A 组成的字符串。
现在就请你为 PAT 写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。
输入格式:
每个测试输入包含 1 个测试用例。第 1 行给出一个正整数 n (≤10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过 100,且不包含空格。
输出格式:
每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出 YES,否则输出 NO。
#include
#include
using namespace std;
bool judge(string s)
{
int count = 0,countm = 0,countl = 0,countr = 0;
char a[3];
for(char c : s)
{
if(c != 'P' && c != 'A' && c != 'T') //仅有三种字符
{
cout << "NO" << endl;
return false;
}
if(c == 'P')
{
if(count == 0)
a[count++] = 'P';
else {cout << "No" << endl;return false;}
}
if(c == 'A')
{
if(count == 1) {a[count++] = 'A';countm++;}
if(count == 0) countl++;
if(count == 2) countm ++;
else countr ++;
}
if(c == 'T')
{
if(count == 2) a[count++] = 'T';
else {cout << "NO" << endl;return false;}
}
}
if(countl * countm != countr) {cout << "NO" << endl;return false;}
if(count == 3) cout << "YES" << endl;
return true;
}
int main()
{
int n = 0;
cin >> n;
string s;
while(n --)
{
cin >> s;
judge(s);
}
return 0;
}
以上是本人代码,希望得到建议
可以将代码简化,把判断条件写在一起,减少if-else的嵌套。
可以将代码拆分成多个函数,比如可以将judge函数拆分成多个函数,以减少函数体的长度,提高可读性。
可以将char a[3]改为string a,以减少空间的占用。