传送门
The student council has a shared document file. Every day, some members of the student council write the sequence TMT (short for Towa Maji Tenshi) in it.
However, one day, the members somehow entered the sequence into the document at the same time, creating a jumbled mess. Therefore, it is Suguru Doujima’s task to figure out whether the document has malfunctioned. Specifically, he is given a string of length n whose characters are all either T or M, and he wants to figure out if it is possible to partition it into some number of disjoint subsequences, all of which are equal to TMT. That is, each character of the string should belong to exactly one of the subsequences.
A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero) characters.
Input
The first line contains an integer t (1≤t≤5000) — the number of test cases.
The first line of each test case contains an integer n (3≤n<105), the number of characters in the string entered in the document. It is guaranteed that n is divisible by 3.
The second line of each test case contains a string of length n consisting of only the characters T and M.
It is guaranteed that the sum of n over all test cases does not exceed 105.
Output
For each test case, print a single line containing YES if the described partition exists, and a single line containing NO otherwise.
思路:
直接遍历整个串,当找到一个‘T’后,就将t的计数器++,当找到一个‘M’后,表示它可以和一个‘T’配对,此时,T的计数器–,我们可以发现,当‘T’的计数器T < 0 || T > n/3时,是不可能满足题目要求的,因而:
#include<bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
#define ll long long
char a[100010];
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
scanf("%s",a+1);
int cnt = n/3;
int m = 0;
int T = 0;
int flag = 0;
for(int i = 1; i <= n; i++)
{
if(a[i] == 'T')
{
T++;
}
else
{
m++;
T--;
}
if(T < 0 || T > n/3)
{
flag = 1;
break;
}
}
if(flag || m != cnt)
{
printf("NO\n");
continue;
}
else
{
printf("YES\n");
continue;
}
}
}