题目描述
The string APPAPT contains two PAT's as substrings. The firstone is formed by the 2nd, the 4th, and the 6th characters,
and the second one is formed by the 3rd, the 4th, and the 6th characters.
Now given any string, you are supposed to tell the number of PAT's contained inthe string.
输入描述:
Each input file contains one test case. For each case, there isonly one line giving a string of no more than 105
characters containing only P, A, or T.
输出描述:
For each test case, print in one line the number of PAT'scontained in the string. Since the result may be a huge number, you only haveto
output the result moded by 1000000007.
输入例子:
APPAPT
输出例子:
2
使用了一个简单的DP思维,使用一个数组存储从左到右一直到I P的数量,然后使用一个数组存储从右到左一直到I T的数量,然后遍历一遍原数组,找到A之后计算这个位置的索引,然后这个A左边的P的数量和这个A的右边的T的数量相乘就是以这个A为中心的PAT的数量
遍历所有的A,结果相加就是最终的结果
记得要取模,还有就是数值不要越界
#include <iostream>
#include <string>
#define theMod 1000000007
using namespace std;
int leftToRightP[100003];
int rightToLeftT[100003];
int main()
{
string startStr;
cin >> startStr;
for (int i = 0; i < startStr.size(); i++)
{
if (startStr[i] == 'P')
{
leftToRightP[i] = leftToRightP[i - 1] + 1;
}
else
{
leftToRightP[i] = leftToRightP[i - 1];
}
}
for (int i = startStr.size()-1; i >=0; i--)
{
if (startStr[i] == 'T')
{
rightToLeftT[i] = rightToLeftT[i + 1] + 1;
}
else
{
rightToLeftT[i] = rightToLeftT[i + 1];
}
}
long long patCount=0;
for (int i = 0; i < startStr.size(); i++)
{
if (startStr[i] == 'A')
{
patCount += (((long long)leftToRightP[i])* rightToLeftT[i]);
patCount %= theMod;
}
}
cout << patCount;
return 0;
}