PAT乙级 1003 我要通过!

把当时的代码放出来,大家共同学习,互相帮助
题目:
在这里插入图片描述
输入样例:

8
PAT
PAAT
AAPATAA
AAPAATAAAA
xPATx
PT
Whatever
APAAATAA

输出样例:

YES
YES
YES
YES
NO
NO
NO
NO

分析:
符合条件的字符串必须只含P,A, T, 且P和T均只能有一个,至少含一个A,首先排除掉不符合上述条件的字符串,然后根据题中条件可以可以获得“答案正确”的分为两类:

1. xPATx

PAT两边的A对称

   PAT
   APATA
   AAPATAA 
   AAAPATAAA
   ......

2. aPbTc正确 —> aPbATca正确

初始aPbTc中 b只能为A,且a=c才能满足正确条件,这里包含两种情况:

(1).a,c为空字符串时:左边首位为P,右边首位为T

   PAT
   PAAT
   PAAAT
   PAAAAT
   ......

(2).a,c为A构成的字符串:以P和T为分隔符分割的到三个字符串,满足:第一个字符串长度 x 第二个字符串长度 = 第三个字符串长度

   APATA               AAPATAA
   APAATAA             AAPAATAAAA            ......
   APAAATAAA           AAPAAATAAAAAA          
   1 x 3 = 3           2 x 3 = 6
   ......              ......                ......

最后分情况讨论就行了,代码如下(Python):

import re
pat = r'PA[A]*T'
for j in range(int(input())):
    flag = False  # 首先假设均不正确(False)
    x = input()
    cA = 0
    cP = 0
    cT = 0
    error = 0
    for i in x:
        if i == 'A':
            cA += 1
        elif i == 'T':
            cT += 1
        elif i == 'P':
            cP += 1
        else:
            error += 1
    if cA >= 1 and cP == 1 and cT == 1 and error == 0:  # 过滤掉不符合条件的字符串
        if re.findall(pat, x):  # 只匹配含'PA[A]*T'的字符串
            found = re.findall(pat, x)[0]
            if found == "PAT":  # 判断满足情况1 就True
                split = found.split('PAT')
                if split[0] == split[1]:
                    flag = True
            else:
                if x[0] == 'P' and x[-1] == 'T':  # 判断满足情况2.(1) 就True
                    flag = True
                else:
                    result = re.split(r'[P|T]', x)  # 以P,T为分隔符分割为三个字符串
                    if len(result[0]) * len(result[1]) == len(result[2]):  # 判断满足情况2.(2) 就True
                        flag = True
    if flag:  # 根据判断输出结果
        print('YES')
    else:
        print('NO')
发布了65 篇原创文章 · 获赞 25 · 访问量 1017

猜你喜欢

转载自blog.csdn.net/chongchujianghu3/article/details/105005626