PAT乙级1003题 我要通过!

题目

1003 我要通过!

分数 20

作者 CHEN, Yue

单位 浙江大学

答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于 PAT 的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。

得到“答案正确”的条件是:

  1. 字符串中必须仅有 P、 A、 T这三种字符,不可以包含其它字符;
  2. 任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串;
  3. 如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a、 b、 c 均或者是空字符串,或者是仅由字母 A 组成的字符串。

现在就请你为 PAT 写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。

输入格式:

每个测试输入包含 1 个测试用例。第 1 行给出一个正整数 n (≤10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过 100,且不包含空格。

输出格式:

每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出 YES,否则输出 NO

输入样例:

10
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA
APT
APATTAA

输出样例:

YES
YES
YES
YES
NO
NO
NO
NO
NO
NO

解题思路:

1.判断条件1:只有P A T 三种字符
2.整理三个条件,得出P T 个数为1,进行判断
3.判断条件2:count_b(中间A的个数)为1,count_a和count_c相等
4.判断条件3:

分析:
 ①PAT(a=0 b=1 c=0) PAAT(0 2 0) PAAAT(0 3 0)
 ②APATA(1 1 1) -> APAATAA(a=1 b=2 c=2) ->  APAAATAAA(a=A b=AAA c=AAA)
    AAPATAA(a=2 b=1 c=2)-->AAPAATAAAA(a=2 b=2 c=4)
    AAAPATAAA(3 1 3) --> AAAPAAPAAAAAA(3 2 6)
可得当count_b >1 时,  count_c = count_a * count_b

代码:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {	
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		String[] s = new String[n]; 
		for(int i = 0; i < n; i++) {
			s[i] = sc.next();
		}
		for(int i = 0; i < n; i++) {
			String temp = s[i];
			int count_p = 0;
			int count_t = 0;
			boolean flag = true;
			//1.判断只有PAT三种字符
			for(int j = 0; j < temp.length(); j++) {
				char c = temp.charAt(j);
				if(c != 'P' && c != 'A' && c != 'T') {
					flag = false;
					break;
				}
				if(c == 'P') count_p++;
				if(c == 'T') count_t++;
			}
			if(flag == false) {//有其他字符
				System.out.println("NO");
				continue; 
			}
			if(count_p != 1 || count_t != 1) { //P和T数目只有一个
				System.out.println("NO");
				continue;
			}
			//此时P和T唯一,其余全是A
			int index_P = temp.indexOf('P');
			int index_T = temp.lastIndexOf('T');
			//条件3中的a b c个数
			int count_a = index_P;
			int count_b = index_T - index_P - 1;
			int count_c = temp.length() - 1 - index_T;
			//中间只有一个A,并且为此*PAT*类型
			if(count_b == 1 && count_a == count_c) { //满足条件二
				System.out.println("YES");
				continue;
			}else if(count_b > 1 && count_c == count_a * count_b){ //满足条件三
				System.out.println("YES");
				continue;
			}else {
				System.out.println("NO");
				continue;
			}
		}
	
	}	
}

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值