Plasticine zebra
Is there anything better than going to the zoo after a tiresome week at work? No wonder Grisha feels the same while spending the entire weekend accompanied by pretty striped zebras.
Inspired by this adventure and an accidentally found plasticine pack (represented as a sequence of black and white stripes), Grisha now wants to select several consequent (contiguous) pieces of alternating colors to create a zebra. Let’s call the number of selected pieces the length of the zebra.
Before assembling the zebra Grisha can make the following operation 0 0 0 or more times. He splits the sequence in some place into two parts, then reverses each of them and sticks them together again. For example, if Grisha has pieces in the order “bwbbw” (here ‘b’ denotes a black strip, and ‘w’ denotes a white strip), then he can split the sequence as bw|bbw (here the vertical bar represents the cut), reverse both parts and obtain “wbwbb”.
Determine the maximum possible length of the zebra that Grisha can produce.
Input
The only line contains a string s s s ( 1 ≤ ∣ s ∣ ≤ 1 0 5 1 \le |s| \le 10^5 1≤∣s∣≤105, where ∣ s ∣ |s| ∣s∣ denotes the length of the string s s s) comprised of lowercase English letters ‘b’ and ‘w’ only, where ‘w’ denotes a white piece and ‘b’ denotes a black piece.
Output
Print a single integer — the maximum possible zebra length.
Example
input
bwwwbwwbw
output
5
input
bwwbwwb
output
3
Note
In the first example one of the possible sequence of operations is bwwwbww|bw → \to → w|wbwwwbwb → \to → wbwbwwwbw, that gives the answer equal to 5 5 5.
In the second example no operation can increase the answer.
Tutorial
根据题意,我们可以将题意理解为将字符串 s s s 进行一个切割,从切割位置开始从左到右循环判断,到达字符串末尾后回到开头,直到回到切割位置
由于将字符串前后分开判断有多长的“斑马线”过于麻烦,所以可以将两个同样的字符串 s s s 拼接起来,然后从前往后进行一次遍历即可,但这样可能会出现重合判断的情况,所以最后只需要对答案和原字符串长度取一个最小值即可,即 min ( a n s , ∣ s ∣ ) \min(ans, |s|) min(ans,∣s∣)
时间复杂度为 O ( n ) \mathcal O(n) O(n)
Solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int ans = 1, cnt = 1;
string s;
cin >> s;
s += s;
for (int i = 1; i < s.size(); ++i) {
if (s[i] != s[i - 1]) {
++cnt;
} else {
cnt = 1;
}
ans = max(ans, cnt);
}
cout << min(ans, (int)(s.size() / 2)) << endl;
return 0;
}