【一次过】交错01串

题目描述

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

输入描述:

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

输出描述:

输出一个整数,表示最长的满足要求的子串长度。

示例1

输入

111101111

输出

3

解题思路1:

双指针。

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            char[] chars = sc.nextLine().toCharArray();
            int l=0, r=0;
            int res = 0;
            
            while(r < chars.length - 1){
                if(chars[r] != chars[r+1])
                    r++;
                else if(l == r){
                    r++;
                    l++;
                }else if(chars[r] == chars[r+1])
                    l++;
                
                res = Math.max(res, r-l+1);
            }
            
            System.out.print(res);
        }
    }
}

解题思路2:

遍历字符串,记录每个位置的最大01串长度

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            char[] chars = sc.nextLine().toCharArray();
            int res = 1;
            int temp = 1;
            
            for(int i=0; i<chars.length-1; i++){
                if(chars[i] != chars[i+1]){
                    temp++;
                    res = Math.max(res, temp);
                }else
                    temp = 1;
            }
            
            System.out.print(res);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值