【TP SRM 703 div2 250】AlternatingString

Problem Statement

A string of zeros and ones is called an alternating string if no two adjacent characters are the same. Examples of alternating strings: “1”, “10101”, “0101010101”. You are given a string s. Each character of s is a ‘0’ or a ‘1’. Please find the longest contiguous substring of s that is an alternating string. Return the length of that substring.
Definition

Class:
AlternatingString
Method:
maxLength
Parameters:
string
Returns:
int
Method signature:
int maxLength(string s)
(be sure your method is public)
Limits

Time limit (s):
2.000
Memory limit (MB):
256
Stack limit (MB):
256

Constraints

s will contain between 1 and 50 characters, inclusive.

Each character in s will be ‘0’ or ‘1’.
Examples
0)

“111101111”
Returns: 3
Among all substrings, there are 5 different alternating strings: “1”, “0”, “10”, “01”, “101”. The one with maximal length is “101” and the length is 3.
1)

“1010101”
Returns: 7
The string s itself is an alternating string.
2)

“000011110000”
Returns: 2
Note that a substring must be contiguous. The longest alternating substrings of this s are “01” and “10”. The string “010” is not a substring of this s.
3)

“1011011110101010010101”
Returns: 8

4)

“0”
Returns: 1

【题目链接】:

【题解】

找连续的01串。找长度最长的那个长度为多少.
枚举下就可以了;
应该也有O(n)的方法.
就是直接顺序往前找就可以了.
如果遇到了停顿的地方就尝试更新一下最大值并且让len=0;
因为看到长度最大为50就写了个暴力

【完整代码】

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <string>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

//const int MAXN = x;
const int dx[5] = {0,1,-1,0,0};
const int dy[5] = {0,0,0,-1,1};
const double pi = acos(-1.0);

class AlternatingString
{
    public:
    int maxLength(string s)
    {
        int len = s.size();
        int ans = 0;
        rep1(i,0,len-1)
            {
                int j = i+1;
                while (j<=len-1 && s[j]!=s[j-1])
                    j++;
                ans = max(ans,j-i);
            }
        return ans;
    }
};

转载于:https://www.cnblogs.com/AWCXV/p/7626821.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值