leetcode-1784-easy

Check if Binary String Has at Most One Segment of Ones

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'.

思路一:刚开始理解错了,意味连续两个'1'才是连续。搞清楚后直接用正则 0+ 分割字符串

public boolean checkOnesSegment(String s) {
    return s.split("0+").length == 1;
}

思路二:看了题解,发现只要判断字符是否包含"01"就行,因为字符已经是"1"开头,所以只要出现"01",说明已经不符合条件

posted @ 2022-11-08 19:42  iyiluo  阅读(21)  评论(0)    收藏  举报