Problem Description
Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.
Key Insights
- The string consists of characters '0' and '1', with the first character guaranteed to be '1'.
- We need to check if the ones in the string are contiguous, meaning there should not be any '0' between two segments of '1'.
- A valid string will either have all '1's together or just a single segment of '1's surrounded by '0's.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) since we are only using a few variables for counting.
Solution
To determine if the binary string has at most one segment of ones, we can iterate through the string and keep track of the transitions between '0's and '1's. We will count how many times we encounter a transition from '0' to '1'. If we find more than one such transition, we can conclude that there are multiple segments of '1's, and we should return false. If there is at most one transition, we return true.