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

题目描述

这是 LeetCode 上的 1784. 检查二进制字符串字段 ,难度为 简单

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

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

如果 s 中 由连续若干个 '1' 组成的字段 数量不超过 1,返回 true。否则,返回 false

示例 1:

1
2
3
4
5
输入:s = "1001"

输出:false

解释:由连续若干个 '1' 组成的字段数量为 2,返回 false

示例 2:
1
2
3
输入:s = "110"

输出:true

提示:

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

模拟

根据题意进行模拟即可。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public boolean checkOnesSegment(String s) {
int n = s.length(), cnt = 0, idx = 0;
while (idx < n && cnt <= 1) {
while (idx < n && s.charAt(idx) == '0') idx++;
if (idx < n) {
while (idx < n && s.charAt(idx) == '1') idx++;
cnt++;
}
}
return cnt <= 1;
}
}

TypeScript 代码:
1
2
3
4
5
6
7
8
9
10
11
function checkOnesSegment(s: string): boolean {
let n = s.length, cnt = 0, idx = 0
while (idx < n && cnt <= 1) {
while (idx < n && s[idx] == '0') idx++
if (idx < n) {
while (idx < n && s[idx] == '1') idx++
cnt++
}
}
return cnt <= 1
};

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def checkOnesSegment(self, s: str) -> bool:
n, cnt, idx = len(s), 0, 0
while idx < n and cnt <= 1:
while idx < n and s[idx] == '0':
idx += 1
if idx < n:
while idx < n and s[idx] == '1':
idx += 1
cnt += 1
return cnt <= 1

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.1784 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。