PAT乙级练习总结
PAT乙级 1003 我要通过! (20分) 第二版有注释,希望我的思路可以帮助你。一、1003题目
输入样例:
8
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA
输出样例:
YES
YES
YES
YES
NO
NO
NO
NO
二、第一版只过了三个点
用了二维数组存储输入的字符串,看了其他大佬写的找了下规律,PT******,P前为ltag,PT之间为tag,T后为rtag,rtag==ltag*tag。
tag必须为1才行,PT应该返回NO。
// 1003第一遍代码
#include<stdio.h>
#include<string.h>
#define MAXS 100
int main(){
int n;
scanf("%d",&n);
pass(n);
return 0;
}
void pass(int n){
char str[n][MAXS];
int i,j,count,star,end,ltag,rtag,tag;
for(i=0;i<n;i++){
scanf("%s",&str[i]);
}
for(i=0;i<n;i++){
count=strlen(str[i]);
if(count<3){
printf("NO\n");
break;
}
ltag=0;rtag=0;tag=0;
//printf("%d\n",count);
for(j=0;j<count;j++){
//printf("%c\n",str[i][j]);
//char *p=str[i][j];
//printf("%c\n",p);
if(str[i][j]!='P'&&str[i][j]!='A'&&str[i][j]!='T'){
printf("NO\n");
}
else{
tag++;
}
}
//printf("%s\n",str[i]);
//printf("%d",tag);
if(tag==count){
star=0;end=count-1;
//printf("%c %c\n",str[i][star],str[i][end]);
while(str[i][star]=='A'||str[i][end]=='A'){
if(str[i][star]=='A'){
ltag++;star++;
}
if(str[i][end]=='A'){
rtag++;end--;
}
}
//printf("%d %d\n",ltag,rtag);
//printf("%d %d\n",star,end);
if(ltag==rtag&&(star+1)==(end-1)&&str[i][star+1]=='A'&&str[i][end-1]=='A'){
printf("YES\n");
}
else{
tag=0,count=0;
star=star+1;
while(star<end){
count++;
if(str[i][star]=='A'){
tag++;
}
star++;
}
if(count==tag&&tag>1){
if(ltag*tag==rtag){
printf("YES\n");
}
else{
printf("NO\n");
}
}else{
printf("NO\n");
}
}
}else{
printf("NO\n");
}
}
}
感觉应该是if太多了,有的地方应该跳出的。
三、第二版
1003 我要通过!
下面展示 成功代码
。
#include<stdio.h>
#define MAXS 100
int main(){
int n;
scanf("%d",&n);//scanf输入记得加&
pass(n);
return 0;
}
void pass(int n){
char str[n][MAXS];//二维数组存输入进来的字符串
int i,j,count,flag,star,end,ltag,tag,rtag;
for(i=0;i<n;i++){
scanf("%s",str[i]);
}
/*for(i=0;i<n;i++){
printf("%s\n",str[i]);
}*/
for(i=0;i<n;i++){
flag=0;//flag标记字符串是否全是PAT组成的
count=strlen(str[i]);//算一下第i个字符串长度
if(count<3){
//如果字符串要是小于3就肯定返回NO了
flag=1;
}
for(j=0;j<count;j++){
//若字符串中有一个不是PAT的flag变化
if(str[i][j]!='P'&&str[i][j]!='A'&&str[i][j]!='T'){
flag++;
}
}
if(flag==0){
//字符串都为PAT组成时
star=0;end=count-1;
ltag=tag=rtag=0;
while(str[i][star]=='A'||str[i][end]=='A'){
//从头和尾向中间推进
if(str[i][star]=='A'){
ltag++;star++;
}
else if(str[i][end]=='A'){
rtag++;end--;
}
}
//printf("%c %c\n",str[i][star],str[i][end]);
if(str[i][star]=='P'&&str[i][end]=='T'){
//要保证字符串中P在T前
star++;
while(str[i][star]=='A'){
if(str[i][star]=='A'){
tag++;star++;
}
else{
break;//P和T之间如果有不是A的则跳出
}
}
//printf("%d %d %d\n",tag,star,end);
if(star==end){
//若PT中间 都为A则star和end相等
if(ltag*tag==rtag){
printf("YES\n");
}
else{
printf("NO\n");
}
}
else{
//若中间出现不是A的则star和end不等输出NO
printf("NO\n");
}
}
else{
printf("NO\n");
}
}
else{
printf("NO\n");
}
}
}