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.
Examples
Input ABA Output NO
Input BACFAB Output YES
Input AXBYBXA Output NO
Note
In the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".
In the second sample test there are the following occurrences of the substrings: BACFAB.
In the third sample test there is no substring "AB" nor substring "BA".
很简单的一道题,我弄了有会了。先是想的不用记录字符串,直接判断。这种只正向判断了AB、BA,ABAXXXAB没过!!
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
char c;
int flag=0;
bool a=0,b=0;
while((c=getchar())!='\n')
{
if(flag)
{
if(flag==1&&c=='B')
{
a=1;
}
else if(flag==2&&c=='A')
{
b=1;
}
flag=0;
}
else
{
if(!a&&c=='A') flag=1;
else if(!b&&c=='B') flag=2;
}
}
if(a&&b) printf("YES\n");
else printf("NO\n");
return 0;
}
需要记录数组,走两个方向。即先AB,再BA,或先BA,再AB。判断两种方法中可行的。
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
string s,ss;
cin>>s;
int len=s.length();
ss=s;
bool a=0,b=0,c=0,d=0;
for(int i=0;i<len-1;i++)
{
if(s[i]=='A'&&s[i+1]=='B')
{
a=1;s[i]=s[i+1]='C';break;
}
}
for(int i=0;i<len-1;i++)
{
if(s[i]=='B'&&s[i+1]=='A')
{
b=1;break;
}
}
for(int i=0;i<len-1;i++)
{
if(ss[i]=='B'&&ss[i+1]=='A')
{
c=1;ss[i]=ss[i+1]='C';break;
}
}
for(int i=0;i<len-1;i++)
{
if(ss[i]=='A'&&ss[i+1]=='B')
{
d=1;break;
}
}
if((a&&b)||(c&&d)) printf("YES\n");
else printf("NO\n");
return 0;
}