You are given a binary string s
(a string consisting only of ‘0’s and ‘1’s). You need to check if the binary string has at most one contiguous segment of ‘1’s. Return True
if the string contains at most one segment of ‘1’s, otherwise return False
.
s = "1001"
False
s = "110"
True
s
is non-empty.To solve this problem, we’ll:
False
; otherwise, return True
.def checkOnesSegment(s: str) -> bool:
count_segments = 0
in_segment = False
for char in s:
if char == '1':
if not in_segment:
count_segments += 1
if count_segments > 1:
return False
in_segment = True
else:
in_segment = False
return True
# Example usage
print(checkOnesSegment("1001")) # Output: False
print(checkOnesSegment("110")) # Output: True
s
. This is because we traverse the string once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?