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

1003 我要通过!

题目

  判断字符串是否符合给定的规则。更多内容点击标题。

参考博客

分析

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

代码

/**
 * Score 20
 * Run Time 71ms
 * @author wowpH
 * @version 2.1
 */
package problemsets.cn.pintia.wowph.t1003.v2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
	/**
	 * Save n strings.
	 */
	private static String[] str;
	/**
	 * The number of strings in a test case.
	 */
	private static int n;

	/**
	 * Custom input class.
	 * 
	 * @author wowpH
	 */
	private static class Scanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		/**
		 * @return The next token.
		 */
		public String next() {
			String x = null;
			try {
				x = br.readLine();
			} catch (IOException e) {
				System.out.println("Error reading input stream.");
			}
			return x;
		}

		/**
		 * @return The <tt>int</tt> scanned from the input.
		 */
		public int nextInt() {
			int x = 0;
			try {
				x = Integer.parseInt(next());
			} catch (NumberFormatException e) {
				System.out.println("Error converting String to Integer.");
			}
			return x;
		}
	}

	/**
	 * Enter the number of strings and an array of strings.
	 */
	private static void input() {
		Scanner sc = new Scanner();
		n = sc.nextInt();
		str = new String[n]; // 保存字符串
		for (int i = 0; i < n; i++) {
			str[i] = sc.next();
		}
	}

	/**
	 * Determines whether the string with <tt>index</tt> in the string array
	 * <tt>str</tt> is correct.
	 * 
	 * @param index 字符串数组的下标,指向当前需要判断的字符串
	 * @return <tt>true</tt> 如果字符串正确
	 */
	private static boolean judge(int index) {
		int numP, numT, numOther; // 'P'的个数,'T'的个数,除了PAT以外的字符的个数
		numP = numT = numOther = 0;
		char[] s = str[index].toCharArray(); // 当前字符串
		int len = s.length; // 长度
		int indexP = 0, indexT = 0; // 'P'的下标,'T'的下标
		// 统计字符的个数,不用统计'A'的个数
		for (int i = 0; i < len; i++) {
			if ('P' == s[i]) {
				numP++;
				indexP = i;
			} else if ('T' == s[i]) {
				numT++;
				indexT = i;
			} else if ('A' != s[i]) {
				numOther++;
			}
		}
		if (1 != numP || 1 != numT || 0 != numOther || indexT - indexP <= 1) {
			return false;
		}
		// 核心代码
		if (indexP * (indexT - indexP - 1) != (len - indexT - 1)) {
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		input(); // 输入
		for (int i = 0; i < n; i++) {
			if (judge(i)) {
				System.out.println("YES"); // 正确
			} else {
				System.out.println("NO"); // 错误
			}
		}
	}

}

补充

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

备注

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

原文地址:https://www.cnblogs.com/wowpH/p/11060791.html