2021-7-25 Two Substrings

难度 1500

题目 Codeforces:

A. Two Substrings
time limit per test
2 seconds
memory limit per test
256 megabytes

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.

Keyword
non-overlapping 不重叠的
 
题目解析
题目大意是给出一个很长的字符串,要求判断里面是否有不重叠的AB和BA
举个例子ABA不行,因为AB和BA的B是重叠的,ABACAB可以,因为第二个AB和第一个BA并不重叠。
所以简单的遍历,找第一个AB后再找第一个BA,如果找不到,那么再重新找第一个BA后找第一个AB,这样就可以避免出现因为先找到一项另一项原本会出现但却因为重叠不成立的情况。
解析完毕,以下是参考代码
 1 #include<iostream>
 2 #include<string>
 3 #include<string.h>
 4 using namespace std;
 5 int main()
 6 {
 7     string s; cin >> s;
 8     bool tf1 = 1, tf2 = 1;
 9     for (int i = 0; i < s.size()-1; i++)
10     {
11         if (s[i] == A && s[i + 1] == B)
12         {
13             if (tf1)
14                 for (int j = i + 2; j < s.size(); j++)
15                 {
16                     if (s[j] == B && s[j + 1] == A)
17                     {
18                         cout << "YES" << endl;
19                         return 0;
20                     }
21                 }
22             if (tf1) tf1 = 0;
23         }
24         else if (s[i] == B && s[i + 1] == A)
25         {
26             if (tf2)
27                 for (int j = i + 2; j < s.size()-1; j++)
28                 {
29                     if (s[j] == A && s[j + 1] == B)
30                     {
31                         cout << "YES" << endl;
32                         return 0;
33                     }
34                 }
35             if (tf2)tf2 = 0;
36         }
37         if (!tf1 && !tf2)break;
38     }
39     cout << "NO";
40     return 0;
41 }

 

2021-7-25 Two Substrings

上一篇:kubesphere3.0安装及验证


下一篇:8.面向对象