20221003 - 1784. Check if Binary String Has at Most One Segment of Ones 检查二进制字符串

213 阅读1分钟

Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.

Example 1

Input: s = "1001"
Output: false
Explanation: The ones do not form a contiguous segment.

Example 2

Input: s = "110"
Output: true

Constraints

  • 1 <= s.length <= 100
  • s[i] is either '0' or '1'.
  • s[0] is '1'.

Solution

题意理解:判断第一个字符为 1 的字符串是否只有一组连续的 1

自己的做法是指针前推,先是若干个 1 ,然后是若干个 0 ,如果最后退出循环时没有停在末尾,说明后面还有 1 ,返回 false。

bool checkOnesSegment(char * s){
    int i = 0;
    while (s[i] == '1') i++;
    while (s[i] == '0') i++;
    if (s[i]) return false;
    else return true;
}

题解做法是说因为前导为 1 ,不可能出现 01 子串

class Solution:
    def checkOnesSegment(self, s: str) -> bool:
        return '01' not in s

题目链接:1784. 检查二进制字符串字段 - 力扣(LeetCode)