Check if Binary String Has at Most One Segment of Ones Problem
#1784
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1784.
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 string has two segments of size 1.
Example 2:
Input: s = "110"
Output: true
Constraints:
1 <= s.length <= 100s[i]is either'0'or'1'.s[0]is'1'.
Solution
Approach: Look for "01"
The string has no leading zeros, so it starts with 1. If it has a second segment of ones, the first segment must end in some 0 and a 1 must follow later, so the string contains the substring "01".
On the other hand, if there is no "01", the string looks like 1...10...0, which is a single segment of ones. So the answer is true exactly when "01" does not occur in s.
Complexity: O(n) time and O(1) space.
class Solution:
def checkOnesSegment(self, s: str) -> bool:
return '01' not in s