Check if Binary String Has at Most One Segment of Ones

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def checkOnesSegment(self, s: str) -> bool:
        # Step 1: Find the index of the first zero
        first_zero_index = s.find('0')

        # Step 2: If there is no zero in the string, the entire string is one segment of ones
        if first_zero_index == -1:
            return True

        # Step 3: If there are any ones after the first zero, return False, else return True
        remaining_string = s[first_zero_index:]
        if '1' in remaining_string:
            return False
        else:
            return True

In this code:

  1. We first find the index of the first ‘0’ in the string.
  2. If there’s no ‘0’ in the string, then the entire string is a contiguous segment of ones, and we return True.
  3. If there are any ‘1’s in the string after the first ‘0’, then there’s more than one contiguous segment of ones, and we return False.
  4. If there are no ‘1’s after the first ‘0’, then there’s only one contiguous segment of ones, and we return True.