CF Two Substrings

时间:2023-11-11 19:55:44
Two Substrings
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

Input

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Output

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

Sample test(s)
input
ABA
output
NO
input
BACFAB
output
YES
input
AXBYBXA
output
NO

找到每组AB和BA的起点坐标,保存起来,然后用最远的一个BA的坐标减去最近的一个AB,或者最远的一个AB减去一个最近的BA,如果两者的差大于等于2,那么就YES.
#include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <climits>
using namespace std; int main(void)
{
char s[];
int ab[],ba[];
int p_ab = ,p_ba = ; scanf("%s",s);
for(int i = ;s[i];i ++)
{
if(s[i] == 'A' && s[i + ] == 'B')
{
ab[p_ab] = i;
p_ab ++;
}
else if(s[i] == 'B' && s[i + ] == 'A')
{
ba[p_ba] = i;
p_ba ++;
}
}
if(!p_ab || !p_ba)
{
puts("NO");
return ;
}
sort(ab,ab + p_ab);
sort(ba,ba + p_ba);
if(abs(ab[] - ba[p_ba - ]) >= || abs(ba[] - ab[p_ab - ]) >= )
puts("YES");
else
puts("NO"); return ;
}