您的位置:首页 > 其它

PAT Basic Level 1003. 我要通过!(20)

2014-03-13 15:21 267 查看
【来源】

1003. 我要通过!(20)

【分析】

为了通过得到可爱的红色的答案正确需要满足一定的条件,具体判断时思路如下:

若有除了"PAT"以外的字符出现,答案错误;
若字符串中有"PAT"字符子串,则看"PAT"前后是否相等且均为空串或仅由'A'构成的字符串,如果是,答案正确,否则,答案错误;
若字符串中有'P'和'T'且'P'在'T'前面,那么整个字符串被分为3部分:头、中间和尾部。三个部分必须均为'A'构成的字符串或是空串。如果头部的长度等于中间的长度与尾部的长度之积,则答案正确,否则答案错误。

【源码】

#include <iostream>
#include <string>
using namespace std;

bool onlyA(const string& s)
{
for (int i = 0; i < s.size(); ++i)
{
if (s[i] != 'A'){
return false;
}
}

return true;
}

bool pass(const string& s)
{
if (!(s.find('P') != string::npos && s.find('A') != string::npos
&& s.find('T') != string::npos))
{
return false;
}

if (s.find("PAT") != string::npos)
{
size_t pos = s.find("PAT");
string head = s.substr(0, pos);
string tail = s.substr(pos + 3);
if (head == tail && onlyA(head)){
return true;
}
else{
return false;
}
}

size_t pPos = s.find('P');
size_t tPos = s.find('T');

if (pPos != string::npos && tPos != string::npos
&& pPos < tPos){
string head = s.substr(0, pPos);
string middle = s.substr(pPos+1, tPos-pPos-1);
string tail = s.substr(tPos+1);

if (onlyA(head) && onlyA(middle) && onlyA(tail)){
if (tail.length() == middle.length() * head.length()){
return true;
}
}
}

return false;
}

int main()
{
int n;
cin >> n;

for (int i = 0; i < n; ++i)
{
string s;
cin >> s;

if (pass(s))
{
cout << "YES\n";
}
else
{
cout << "NO\n";
}
}
return 0;
}


【点评】

此题考察稍复杂的字符串处理。第三个判断条件需要洞察出字符串的规律所在。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT string