跳转至

1784. 检查二进制字符串字段

题目描述

给你一个二进制字符串 s ,该字符串 不含前导零

如果 s 包含 零个或一个由连续的 '1' 组成的字段 ,返回 true​​​ 。否则,返回 false

 

示例 1:

输入:s = "1001"
输出:false
解释:由连续若干个 '1' 组成的字段数量为 2,返回 false

示例 2:

输入:s = "110"
输出:true

 

提示:

  • 1 <= s.length <= 100
  • s[i]​​​​ 为 '0''1'
  • s[0]'1'

解法

方法一:0 后面不能有 1

注意到字符串 \(s\) 不含前导零,说明 \(s\) 以 '1' 开头。

若字符串 \(s\) 存在 "01" 串,那么 \(s\) 就是形如 "1...01..." 的字符串,此时 \(s\) 出现了至少两个连续的 '1' 片段,不满足题意,返回 false

若字符串 \(s\) 不存在 "01" 串,那么 \(s\) 只能是形如 "1..1000..." 的字符串,此时 \(s\) 只有一个连续的 '1' 片段,满足题意,返回 true

因此,只需要判断字符串 \(s\) 是否存在 "01" 串即可。

时间复杂度 \(O(n)\)。其中 \(n\) 为字符串 \(s\) 的长度。空间复杂度 \(O(1)\)

1
2
3
class Solution:
    def checkOnesSegment(self, s: str) -> bool:
        return '01' not in s
1
2
3
4
5
class Solution {
    public boolean checkOnesSegment(String s) {
        return !s.contains("01");
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool checkOnesSegment(string s) {
        return s.find("01") == -1;
    }
};
1
2
3
func checkOnesSegment(s string) bool {
    return !strings.Contains(s, "01")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function checkOnesSegment(s: string): boolean {
    let pre = s[0];
    for (const c of s) {
        if (pre !== c && c === '1') {
            return false;
        }
        pre = c;
    }
    return true;
}
1
2
3
4
5
impl Solution {
    pub fn check_ones_segment(s: String) -> bool {
        !s.contains("01")
    }
}

方法二

1
2
3
function checkOnesSegment(s: string): boolean {
    return !s.includes('01');
}

评论