交错01串

如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如: "1","10101","0101010"都是交错01串。
小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。 

输入描述:
输入包括字符串s,s的长度length(1 ≤ length ≤ 50),字符串中只包含'0'和'1'



输出描述:
输出一个整数,表示最长的满足要求的子串长度。
输入例子1:
111101111
输出例子1:
3

构造两个交错串然后对比就行了

#include <bits/stdc++.h>
using namespace std;
int main() {
    string s;
    cin >> s;
    string s1;
    string s2;
    int x = 1;
    for (int i = 0; i < s.size(); ++i){
        if(i%2==0)s1+=(x+'0');
        else s1+=('0');
    }
    for (int i = 0; i < s.size(); ++i){
        if(i%2==0)s2+='0';
        else s2+=(x+'0');
    }
    //cout << s1 << endl <<s2<<endl;
    int cnt = 0;
    int ans = 0;
    for(int i = 0; i < s.size(); ++i) {
        if(s1[i]==s[i]) {
            cnt++;
        } else{
            ans =max(ans,cnt);
            cnt = 0;
        }
    }
    ans = max(ans,cnt);
    cnt=0;
    for(int i = 0; i < s.size(); ++i) {
        if(s2[i]==s[i]) {
            cnt++;
        } else{
            ans =max(ans,cnt);
            cnt = 0;
        }
    }
    ans = max(ans,cnt);
    cout << ans << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/pk28/p/7419982.html