有个坑点是第三条件是个递归式,比如说APATA(假设我们叫这个字符串为a)是正确的,那么APAATAA(b)也是正确的。既然b是正确的,那么由b得:APAAATAAA(c)也是正确的,以此类推。现在我们要做的就是把c逐步还原到a,判定a是否满足第二条件。
还有第一,二条件里其实隐含了P,T只能出现一次,而且必然要出现,而A可以出现好多次。其他应该没什么要注意的。
附上本人优雅的代码~
#include <iostream>
#include <string>
using namespace std;
bool sec_con(string str) { //判定字符串是否满足第二条件
int length = str.length();
int mid = length / 2;
if (str[mid - 1] != 'P' || str[mid] != 'A' || str[mid + 1] != 'T')
return false;
for (int i = 0; i < mid-1; i++) {
if (str[i] != 'A' || str[length-i-1] != 'A')
return false;
}
return true;
}
bool trd_con(string str) { //判断字符串是否满足第三条件,第三条件实际上是个递归的意思
int length = str.length();
int ip = -1, it = -1;
for (int i = 0; i < length; i++) {
if (str[i] == 'P')
ip = i;
if (str[i] == 'T')
it = i;
}
if (it - ip == 1) return false;
if (it - ip == 2 && sec_con(str))
return true;
string a;
for (int i = 0; i < ip; i++)
a += str[i];
string c;
for (int i = it + 1; i < length - a.length(); i++)
c += str[i];
string b;
for (int i = ip + 1; i < it - 1; i++)
b += str[i];
string sum = a + 'P' + b + 'T' + c;
return trd_con(sum);
}
int main()
{
int n;
cin >> n;
while (n--) {
string str;
cin >> str;
int length = str.length();
int P = 0, T = 0;
int indexofP = -1, indexofT = -1;
bool A = false;
for (int i = 0; i < length; i++) {
if (str[i] == 'A')
A = true;
if (str[i] == 'P') {
P++;
indexofP = i;
}
if (str[i] == 'T') {
T++;
indexofT = i;
}
}
if (indexofT - indexofP < 0 || P >1 || indexofP ==-1 || T > 1 || indexofT == -1 || A == false) {
cout << "NO" << endl;
continue;
}
if (sec_con(str))
cout << "YES" << endl;
else if (trd_con(str))
cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}