题目:
“答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。
得到“答案正确”的条件是:
1. 字符串中必须仅有P, A, T这三种字符,不可以包含其它字符;
2. 任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串;
3. 如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a, b, c 均或者是空字符串,或者是仅由字母 A 组成的字符串。
输入格式: 每个测试输入包含1个测试用例。第1行给出一个自然数n (<10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过100,且不包含空格。
输出格式:每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出YES,否则输出NO。
输入样例:8 PAT PAAT AAPATAA AAPAATAAAA xPATx PT Whatever APAAATAA输出样例:
YES YES YES YES NO NO NO NO
题解:
属于找规律题,需要注意大量的细节。本题部分参考了https://www.liuchuo.net/archives/460该博客
有一点不解的是,当使用cin.getline(s, 110)输入字符串的时候,有一组数据会“段错误”,改为cin后正常。
代码:
#include <iostream>
#include <cstring>
using namespace std;
bool judge(char s[])
{
int len = strlen(s);
int cntL = 0, cntM = 0, cntR = 0, idx;
int posP, posT;
bool mark[5] = {false};
for(idx = 0; idx < len; idx++)
{
if(s[idx] == 'P') //若s中没有出现P、A、T或者出现了其他字符则return false
mark[0] = true;
else if(s[idx] == 'A')
mark[1] = true;
else if(s[idx] == 'T')
mark[2] = true;
else
return false;
if(s[idx] == 'P')
{
posP = idx;
for(int j = idx - 1; j >= 0; j--)
{
if(s[j] != 'A')
return false;
cntL++; //cntL统计P左侧的A的数量
}
}
if(s[idx] == 'T')
{
posT = idx;
for(int j = posP + 1; j < posT; j++)
{
if(s[j] != 'A')
return false;
cntM++; //cntM统计P和T之间的A的数量
}
for(int j = posT + 1; j < len; j++)
{
if(s[j] != 'A')
return false;
cntR++; //cntR统计T右侧的A的数量
}
}
}
if(mark[0] == false || mark[1] == false || mark[2] == false)
return false;
if(cntL * cntM != cntR) //A的数量满足cntL * cntM == cntR
return false;
else
return true;
}
int main()
{
int n;
char s[110];
cin >> n;
// getchar();
while(n--)
{
cin >> s;
if(judge(s))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}