PAT B exam - I want to pass!

"Correct answer" is the most joy automatic reply sentence topic given system. This title belongs to the PAT of "correct answer" big delivery - just read the string following conditions are satisfied, the system will output "correct answer", otherwise outputs "Wrong Answer."

Get the "correct answer" conditions are:

  1. String must have only P, A, T of the three characters, the characters may not contain other;
  2. The string of arbitrary shape can be obtained xPATx "correct answer", or where x is the empty string, or a string consisting only of letters A;
  3. If aPbTc is correct, then aPbATca is correct, wherein a, b, c or all the empty string, or a string consisting only of letters A.

Now ask you to write a PAT referee program automatically determines which strings can get "the answer right".

Input formats:

Each test comprises a test input. Line 1 is given a positive integer n (<10), is the number of strings to be detected. Next, one row for each string, the string length of not more than 100, no spaces.

Output formats:

The detection result row for each string, if the string can get "correct answer", the output YES, otherwise output NO.

Sample input:

8
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA

Sample output:

YES
YES
YES
YES
NO
NO
NO
NO

Thinking

From: https: //blog.csdn.net/whl_program/article/details/76652890

Code

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

char s[110],ans[11][4];
int k=0;

int main()
{
	int front,mid,behind; //前中后的A的个数
	int n,i,j;
	int pass;	//为1表示通过
	int see_p,see_t; //为1表示遇见过P或T了
	cin>>n;
	for( i=0; i<n; i++)
	{
		scanf("%s",&s);
		front=0,mid=0,behind=0;
		see_p=0,see_t=0,pass=-1;
		for(j=0; j<strlen(s); j++)
		{
			if(s[j]!='A' && s[j]!='P' && s[j]!='T' ||
			s[j]=='P' && s[j+1]!='A') //P和A不挨着、有其他字母 不行
			{
				pass=0; break;
			}
			if(s[j]=='P') see_p=1;
			else if(s[j]=='T') see_t=1;

			if (s[j]=='A' && !see_p) front++;
			else if(s[j]=='A' && see_p && !see_t) mid++;
			else if(s[j]=='A' && see_t)	 behind++;
		}
		//没有P和T不行 ↓↓↓↓↓↓↓
		if(j==strlen(s) && front*mid==behind && see_p && see_t) 
			pass=1;
			
		if(pass!=1)
			strcpy(ans[k++],"NO");
		else if(pass==1)
			strcpy(ans[k++],"YES");
	}
	for(i=0; i<n; i++)
	{
		cout<<ans[i];
		if(i<k-1) cout<<endl;
	}
}
Published 35 original articles · won praise 2 · Views 902

Guess you like

Origin blog.csdn.net/qq_45735810/article/details/104098195