题目形容

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

Tag : 「模仿」

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

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

如果 s 中 由间断若干个 '1' 组成的字段 数量不超过 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'

模仿

依据题意进行模仿即可。

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
  • 工夫复杂度:$O(n)$
  • 空间复杂度:$O(1)$

最初

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

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

为了不便各位同学可能电脑上进行调试和提交代码,我建设了相干的仓库:https://github.com/SharingSou... 。

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

更多更全更热门的「口试/面试」相干材料可拜访排版精美的 合集新基地

本文由mdnice多平台公布