Two Substrings
time limit per test
2 secondsmemory limit per test
256 megabytesinput
standard inputoutput
standard outputYou 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[100005]; int ab[100005],ba[100005]; int p_ab = 0,p_ba = 0; scanf("%s",s); for(int i = 0;s[i];i ++) { if(s[i] == 'A' && s[i + 1] == 'B') { ab[p_ab] = i; p_ab ++; } else if(s[i] == 'B' && s[i + 1] == 'A') { ba[p_ba] = i; p_ba ++; } } if(!p_ab || !p_ba) { puts("NO"); return 0; } sort(ab,ab + p_ab); sort(ba,ba + p_ba); if(abs(ab[0] - ba[p_ba - 1]) >= 2 || abs(ba[0] - ab[p_ab - 1]) >= 2) puts("YES"); else puts("NO"); return 0; }