合法字符串僅含P、A、T三字符,滿足:
1. xPATx合法,x為空串或純A串。
2. 若aPbTc合法,則aPbATca合法(a,b,c為空或純A)。
等價數學條件:設P前A數為a,P-T間A數為b,T後A數為c。則必須滿足:
a ≥ 0, b ≥ 1, c = a × b,且整串無其他字符。
P、T各出現1次,A至少1次,無其他字符。P、T位置posP、posT,計算a = posP、b = posT - posP - 1、c = len - posT - 1。a * b == c。
#include
#include
#include
#define MAXL 101
int main() {
int n; scanf("%d", &n);
char **s = malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
s[i] = malloc(MAXL);
scanf("%s", s[i]);
}
for (int i = 0; i < n; i++) {
int cntP=0, cntT=0, cntA=0, other=0;
char *pP=NULL, *pT=NULL;
for (int j=0; s[i][j]; j++) {
if (s[i][j]=='P') { cntP++; pP=&s[i][j]; }
else if (s[i][j]=='T') { cntT++; pT=&s[i][j]; }
else if (s[i][j]=='A') cntA++;
else other=1;
}
int ok = (cntP==1 && cntT==1 && cntA>0 && !other);
if (ok) {
int a = pP - s[i];
int b = pT - pP - 1;
int c = strlen(pT) - 1;
ok = (a * b == c);
}
puts(ok ? "YES" : "NO");
}
return 0;
}
| 輸入 | a | b | c | a×b==c | 結果 |
|---|---|---|---|---|---|
| PAT | 0 | 1 | 0 | 0==0 ✓ | YES |
| PAAT | 0 | 2 | 0 | 0==0 ✓ | YES |
| AAPATAA | 2 | 1 | 2 | 2==2 ✓ | YES |
| AAPAATAAAA | 2 | 2 | 4 | 4==4 ✓ | YES |
| xPATx | - | - | - | 含非法字符 | NO |