PAT(B)1003 我要通过!(Java)

68 篇文章 3 订阅
16 篇文章 0 订阅

题目链接:1003 我要通过!


题目

判断字符串是否符合给定的规则。完整题目

分析

规律:num_a * num_b = num_c。字符串a中字母A的个数乘以字符串b中字母A的个数 等于 字符串c中字母A的个数。


代码

/**
 * Score 20
 * Run Time 101ms
 * @author wowpH
 * @version 3.0
 * @date 2019-11-16 21:00:03
 * @from https://blog.csdn.net/pfdvnah/article/details/90116301
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	private static boolean judge(String str) {
		int numP, numT, numOther; // 'P'的个数,'T'的个数,除了PAT以外的字符的个数
		numP = numT = numOther = 0;
		char[] arr = str.toCharArray(); // 当前字符串
		int len = arr.length; // 长度
		int indexP = 0, indexT = 0; // 'P'的下标,'T'的下标
		// 统计字符的个数,不用统计'A'的个数
		for (int i = 0; i < len; i++) {
			if ('P' == arr[i]) {
				++numP;
				indexP = i;
			} else if ('T' == arr[i]) {
				++numT;
				indexT = i;
			} else if ('A' != arr[i]) {
				numOther++;
			}
		}
		if (1 != numP || 1 != numT || 0 != numOther || indexT - indexP <= 1) {
			return false;
		}
		// 核心代码
		// 通过第3个条件可以发现,中间加1个'A'的时候,右边加了1个a,
		// 所以num_a * num_b = num_c时,合法
		if (indexP * (indexT - indexP - 1) != (len - indexT - 1)) {
			return false;
		}
		return true;
	}

	public static void main(String[] args)	throws NumberFormatException,
											IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		while ((n--) > 0) {
			String str = br.readLine();
			if (judge(str)) {
				System.out.println("YES");
			} else {
				System.out.println("NO");
			}
		}
	}
}

补充

  • 字母P和字母T的个数都为1。
  • 不能有其他字母。
  • 字母P和字母T之间至少有1个字母A

备注

刚来PAT没什么经验。这个居然不是多组输入。而且还是一次性读完n个字符串再一次性输出。我还以为是读取一个字符串数出一个结果。


参考ValarMorghulis的博客:https://www.cnblogs.com/valar/p/6142602.html

原文链接:https://blog.csdn.net/pfdvnah/article/details/90116301


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值