Two Substrings

xiaoxiao2021-02-28  96

D - Two Substrings Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u Submit  Status

Description

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 Input

Input ABA Output NO Input BACFAB Output YES Input AXBYBXA Output NO

Hint

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".

好好考虑一下,直接从前往后,从后往前扫描一起就行。

比较low的AC代码:

#include<cstdio> #include<cstring> #include<cctype> #include<algorithm> #include<set> #include<cstring> #include<string> #include<iostream> #include<cmath> using namespace std; char a[100005],b[100005]; int main (){ scanf("%s",a); strcpy(b,a); int n=strlen(a); int flag1=0,flag2=0,k1,k2,m1,m2; for(int i=0;i<n-1;i++){ if(a[i]=='A'&&a[i+1]=='B') { a[i]='0'; a[i+1]='0'; flag1=1; break; } } for(int i = 0; i < n-1; i++) if(a[i]=='B'&&a[i+1]=='A'){ flag2=1; break; } if(flag1&&flag2){ printf("YES\n"); return 0; } flag1=0,flag2=0; for(int i=0;i<n-1;i++){ if(b[i]=='B'&&b[i+1]=='A'&&!flag2){ b[i]='0'; b[i+1]='0'; flag2=1; break; } } for(int i=0;i<n-1;i++) if(b[i]=='A'&&b[i+1]=='B'&&!flag1) { flag1=1; break; } if(flag1&&flag2) printf("YES\n"); else printf("NO\n"); } 到网上看了一下大佬的代码,用到了strstr()函数,代码就简便了许多了。

大佬的代码:

#include<iostream> #include<stdio.h> #include<string.h> using namespace std; char s[100001]; int main(){ char *c; scanf("%s",&s); if((c=strstr(s,"AB"))!=NULL&&strstr(c+2,"BA")!=NULL){ printf("YES\n"); return 0; } if((c=strstr(s,"BA"))!=NULL&&strstr(c+2,"AB")!=NULL){ printf("YES\n"); return 0; } printf("NO\n"); } strstr()具体用法为:

char  str[]= "1234xyz" ; char  *str1= strstr (str, "34" ); cout << str1 << endl; strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。 该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。

转载请注明原文地址: https://www.6miu.com/read-51021.html

最新回复(0)