1784 检查二进制字符串字段

题目描述:
给你一个二进制字符串 s ,该字符串 不含前导零 。
如果 s 最多包含 一个由连续的 ‘1’ 组成的字段 ,返回 true​​​ 。否则,返回 false 。

示例 1:
输入:s = “1001”
输出:false
解释:字符串中的 1 没有形成一个连续字段。

示例 2:
输入:s = “110”
输出:true

提示:
1 <= s.length <= 100
s[i]​​​​ 为 ‘0’ 或 ‘1’
s[0] 为 ‘1’

方法1:
主要思路:解题链接汇总
(1)模拟;
(2)字符串的前半段全为1,后半段全为0,否则false

class Solution {
    
    
public:
    bool checkOnesSegment(string s) {
    
    
        if(s[0]!='1'){
    
    
            return false;
        }
        int index=0;;
        while(index<s.size()&&s[index]=='1'){
    
    
            ++index;
        }
        while(index<s.size()&&s[index]!='1'){
    
    
            ++index;
        }
        return index==s.size();
    }
};

go语言实现

func checkOnesSegment(s string) bool {
    
    
    if s[0]=='0' {
    
    
        return false
    }
    index := 0
    for index<len(s)&&s[index]=='1' {
    
    
        index++
    }
    for index<len(s)&&s[index]=='0' {
    
    
        index++
    }
    return index==len(s)
}

方法2:
主要思路:
(1)若是字符串中出现01这种情形,则错误

class Solution {
    
    
public:
    bool checkOnesSegment(string s) {
    
    
        if(s[0]!='1'){
    
    
            return false;
        }
        for(int i=1;i<s.size();++i){
    
    
            if(s[i]=='1'&&s[i-1]=='0'){
    
    
                return false;
            }
        }
        return true;
    }
};

//go语言实现

func checkOnesSegment(s string) bool {
    
    
    if s[0]=='0'{
    
    
        return false
    }
    for i:=1;i<len(s);i++ {
    
    
        if s[i]=='1'&&s[i-1]=='0' {
    
    
            return false
        }
    }
    return true
}

猜你喜欢

转载自blog.csdn.net/weixin_44171872/article/details/115023176