题目链接: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