codeforces 550A

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

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”,并且不能是“BAB”,有的话输出“YES”,没有输出“NO”,我的想法是输入一个字符记为a,输入第二个字符记为b,如果ab=“AB”,则ab=1,ab=“BA”,则ba=1,依次迭代,ab=1并且ba=1则输出“YES”,否则输出“NO”;在运行过程中发现一个问题,就是在字符串中有“ABA”和“AB”,这个程序只能检测到AB不能检测到BA,考虑到在完善这个程序比较麻烦就找了找其他人是怎么做的,学到了str.find函数。

源程序

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char a, b;
    int ab = 0, ba = 0;
    cin >> a;
    while (cin.get(b))
    {
        if (b != '\n')
        {
            if (a == 'A'&&b == 'B'&&ab != 1)
            {
                ab++;
                cin.get(a);
            }
            else if (a == 'B'&&b == 'A'&&ba != 1)
            {
                ba++;
                cin.get(a);
            }
            else if (ab == 1 && ba == 1)
                break;
            else
                a = b;
            if (a == '\n')
                break;
        }
        else
            break;
    }
    if (ab == 1 && ba == 1)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    return 0;
}
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
string str;
int main()
{
    cin >> str;
    int len = str.size();
    if (len <= 3)
        puts("NO");
    else
    {
        int a = str.find("AB");
        int b = str.find("BA", a + 2);
        int c = str.find("BA");
        int d = str.find("AB", c + 2);
        if ((a != -1 && b != -1) || (c != -1 && d != -1))
            puts("YES");
        else
            puts("NO");
    }
    return 0;
}

原作地址:

http://blog.csdn.net/u013050857/article/details/46660095

posted @ 2018-01-10 10:34  暮雨青枫  阅读(257)  评论(0编辑  收藏  举报