Determine whether all the 1 characters in a binary string appear in a single contiguous block.
Check If Binary String Has At Most One Segment Of Ones
Given a binary string s containing only 0 and 1, determine whether the string contains at most one contiguous segment of 1s.
A segment of 1s is a maximal contiguous block made up entirely of 1 characters. The string is valid if it has either:
- no
1characters at all, or - exactly one block of one or more
1s.
Return true if the string is valid, otherwise return false.
Examples of valid strings
"0""111""0011100"
Examples of invalid strings
"101""110011"
Input Format
- A single binary string
s. scontains only characters'0'and'1'.
Output Format
- Return a boolean value indicating whether
shas at most one segment of1s.
Constraints
1 <= s.lengths[i]is either'0'or'1'
Example 1
Input
s = "110"
Output
true
Explanation
All the 1s are in one contiguous block at the beginning.
Example 2
Input
s = "1001"
Output
false
Explanation
There are two separate blocks of 1s: one at the start and one at the end.
Show 1 more example
Example 3
Input
s = "0000"
Output
true
Explanation
There are no 1s, so the string has at most one segment of 1s.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.