题目信息:
字符串APPAPT中包含了两个单词“PAT”,其中第一个PAT是第2位(P),第4位(A),第6位(T);第二个PAT是第3位(P),第4位(A),第6位(T)。
现给定字符串,问一共可以形成多少个PAT?
输入格式:
输入只有一行,包含一个字符串,长度不超过105,只包含P、A、T三种字母。
输出格式:
在一行中输出给定字符串中包含多少个PAT。由于结果可能比较大,只输出对1000000007取余数的结果。
输入样例:APPAPT输出样例:
2
示例代码1:
这种是检测输入的字符串进行遍历,比较费时,提交超时。
#include <iostream> #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <cctype> using namespace std; char str[100000]; void solve() { int ct=0; for(int i=0;str[i];i++) { if(str[i]=='P') { for(int j=i;str[j];j++) { if(str[j]=='A') { for(int k=j;str[k];k++) { if(str[k]=='T') {ct++;} } continue; } } continue; } } ct=ct%1000000007; cout<<ct<<endl; } int main() { cin>>str; solve(); system("pause"); return 0; }示例代码二:
这种方法是输入一个字符判断一下,是PAT中的哪一个,要检测PAT的个数,我们需要检测PA的个数,检测PA个数,需要知道P和A的个数。
#include <iostream> #include <algorithm> #include <cmath> #include <cstdio> #include <cstring> #include <cctype> using namespace std; void solve() { char str; int nP=0,nPA=0,nPAT=0; while((str=getchar())!='\n') { if(str=='P') { nP++; } else if(str=='A') { if(nP) nPA+=nP; } else if(str=='T') { if(nPA) nPAT=(nPAT+nPA)%1000000007; } } cout<<nPAT<<endl; } int main() { solve(); system("pause"); return 0; }