网易编程题----01串问题

如果一个01串任意两个相邻位置的字符都是不一样的,我们就叫这个01串为交错01串。例如: “1”,”10101”,”0101010”都是交错01串。
小易现在有一个01串s,小易想找出一个最长的连续子串,并且这个子串是一个交错01串。小易需要你帮帮忙求出最长的这样的子串的长度是多少。
输入描述:输入包括字符串s,s的长度length(1 ≤ length ≤ 50),字符串中只包含’0’和’1’
输出描述:输出一个整数,表示最长的满足要求的子串长度。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    string str;
    cin>>str;
    if(str.length() == 1)//如果字符串长度为1,则直接输出1
    {
        cout<<1<<endl;
        return 0;
    }
    int count = 1;
    int temp = 1;
    for(int i = 1; i < str.length(); i ++)
    {
        count ++;
        if(str[i] == str[i-1])//判断当前字符串与上一个字符串是否相等
            count = 1;//如果相等则计数仍置为1
        if(count > temp)
            temp = count;
    }
    cout<<temp<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/imprincess/article/details/81566108