1003. 我要通过!(20)

原题: https://www.patest.cn/contests/pat-b-practise/1003

实现思路:
形如aPbTc, 输出答案正确.
a可以是0个或多个A
b可以是1个或多个A
c可以是0个或多个A
假设a, b, c分别包含x, y, z个A, 则必须必须满足x * z = y

完整代码:

#include <stdio.h>

int isPATString (char *str);

int main () {
    char pstr[120];
    int n;
    int isPAT;
    scanf("%d", &n);

    while (n) {
        scanf("%s", pstr);
        isPAT = isPATString(pstr);
        if (isPAT == 1) {
            printf("YES\n");
        } else if (isPAT == 0) {
            printf("NO\n");
        }
        n--;
    }
    return 0;
}

int isPATString (char *str) {
    char *ph = str; // 指向字符串第1位
    char *pp; // 指向P
    char *pt; // 指向T
    int a = 0;
    int b = 0;
    int c = 0;

    // 先确定字符串中, 只含有PAT这三个字符
    while (*str != '\0') {
        if (*str == 'A') {
            // do nothing
        } else if (*str == 'P') {
            pp = str;
        } else if (*str == 'T') {
            pt = str;
        } else {
            return 0;
        }
        str++;
    }
    // 根据题目描述, P在左T在右, 并且中间至少有一个A
    if (!(pp+1 < pt)) {
        return 0;
    }

    while (*ph != '\0') {
        if (ph < pp) {
            a++;
        } else if (pp < ph && ph < pt) {
            b++;
        } else if (ph > pt) {
            c++;
        }
        ph++;
    }
    if (a*b == c) {
        return 1;
    } else {
        return 0;
    }
}

posted @ 2017-10-08 16:36  阿胜4K  阅读(359)  评论(0编辑  收藏  举报