题目大意:
能否把只含T和M的字符串分成,若干个TMT的子序列,原字符串长度是3的倍数
思路
- 我们看TMT这个串,M前面要有一个T,M后面也要有一个T,并且 cnt(T)=2*cnt(M)
- 那么我们从前往后遍历一遍,看每一个M的前面能否各自匹配到一个T。光是这样还不行,我们还需要从后往前遍历一遍,看每一个M后面能否各自匹配到一个T
- 这样对于每一个M的前后,都有一个单独的T与它匹配,这不就是TMT了吗,同时要判断cnt(T)是否等于2*cnt(M)
AC代码
#include<bits/stdc++.h>
#define ft first
#define sd second
#define mem(a,b) memset(a,b,sizeof a)
#define endl '\n'
#define IOS ios::sync_with_stdio(false),cin.tie(0)
using namespace std;
const int N = 1e5+9;
int a[N];
bool check(int n,string s)
{
int cnt1=0,cnt2=0;//cnt1代表M的个数,cnt2代码T的个数
for(int i=0; i<n; i++)//从前往后
{
if(s[i]=='M')
{
cnt1++;
if(cnt2<cnt1) return false;
}
else cnt2++;
}
if(cnt1*2!=cnt2) return false;
cnt1=cnt2=0;
for(int i=n-1; i>=0; i--)//从后往前
{
if(s[i]=='M')
{
cnt1++;
if(cnt2<cnt1) return false;
}
else cnt2++;
}
return true;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string s;
cin>>s;
if(check(n,s)) puts("YES");
else puts("NO");
}
return 0;
}