題目描述
這是 LeetCode 上的 1784. 檢查二進制字元串字段 ,難度為 簡單。
Tag : 「模拟」
給你一個二進制字元串
s
,該字元串 不含前導零 。
如果
s
包含 零個或一個由連續的
'1'
組成的字段 ,傳回
true
。否則,傳回
false
。
如果
s
中 由連續若幹個
'1'
組成的字段 數量不超過
1
,傳回
true
。否則,傳回
false
。
示例 1:
輸入:s = "1001"
輸出:false
解釋:由連續若幹個 '1' 組成的字段數量為 2,傳回 false
示例 2:
輸入:s = "110"
提示:
-
為s[i]
或'0'
'1'
-
為s[0]
'1'
模拟
根據題意進行模拟即可。
Java 代碼:
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 代碼:
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 代碼:
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
- 時間複雜度:
- 空間複雜度:
最後
這是我們「刷穿 LeetCode」系列文章的第
No.1784
篇,系列開始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道題目,部分是有鎖題,我們将先把所有不帶鎖的題目刷完。
在這個系列文章裡面,除了講解解題思路以外,還會盡可能給出最為簡潔的代碼。如果涉及通解還會相應的代碼模闆。