Problem Description
You are given a string S consisting of 0 and 1. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into 0 by repeating the following operation some number of times.
Choose a contiguous segment [l,r] in S whose length is at least K (that is, r−l+1≥K must be satisfied). For each integer i such that l≤i≤r, do the following: if Si is 0, replace it with 1; if Si is 1, replace it with 0.
Constraints
- 1≤|S|≤105
- Si(1≤i≤N) is either
0
or1
.Input
Input is given from Standard Input in the following format:
S
Output
Print the maximum integer K such that we can turn all the characters of S into 0 by repeating the operation some number of times.
Example
Sample Input 1
010
Sample Output 1
2
We can turn all the characters of S into 0 by the following operations:Perform the operation on the segment S[1,3] with length 3. S is now 101.
Perform the operation on the segment S[1,2] with length 2. S is now 011.
Perform the operation on the segment S[2,3] with length 2. S is now 000.Sample Input 2
100000000
Sample Output 2
8
Sample Input 3
00001111
Sample Output 3
4
题意:给出一个 01 串,要求寻找一个最大长度 k,每次在 01 串中选取长度至少为 k 的区间,将区间内的值取反,通过若干次操作后,使得 01 串变为全 0 串,求这个最大长度 k
思路:
由于要求的是 k 的最大长度,因此无需考虑翻转次数,也就是说最后变成全 0 还是全 1 都不影响结果
对于第 i 个字符来说,假设其前 i-1 个字符相等,且其与前 i-1 个字符不等,即 s[1]=s[2]=...=s[i-1]≠s[i],那么为了最后变为一致的结果,那么一定会选择翻转前 i 个字符,或者翻转后 n-i 个字符
以 00010100 为例,前 3 个字符相同第 4 个字符与前三个不同,为了达到最终所有字符相同,要么翻转前 4 个变为 11100100 然后再进行翻转,要么翻转后 5 个变为 00001011 然后再进行翻转
因此可以去枚举字符串,寻找第 i-1 个字符与第 i 个字符不同的 i,在 i 和 n-i 中去取最大的一个就是每一个字符进行翻转的最大值,由于要求最大的长度 k,因此在每一个字符进行翻转的最大值中选最小的一个即可
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int a[N];
int main(){
string str;
cin>>str;
int len=str.length();
int cnt=0;
for(int i=1;i<len;i++)
if(str[i]!=str[i-1])
a[++cnt]=max(i,len-i);
int res=len;
for(int i=1;i<=cnt;i++)
res=min(res,a[i]);
printf("%d\n",res);
return 0;
}