##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1784.html

# 1784. Check if Binary String Has at Most One Segment of Ones

Easy

## Description

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 ones do not form a contiguous segment.

Example 2:

Input: s = “110”

Output: true

Constraints:

• 1 <= s.length <= 100
• s[i] is either '0' or '1'.
• s[0] is '1'.

## Solution

Loop over s from left to right. For each character, if the character is '1' and its previous character is '0', then the current character is the first character of a segment of ones. Return true only if the number of segments of ones is at most 1.

• class Solution {
public boolean checkOnesSegment(String s) {
int onesSegments = 0;
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == '1') {
if (i == 0 || s.charAt(i - 1) == '0')
onesSegments++;
}
}
return onesSegments <= 1;
}
}

############

class Solution {
public boolean checkOnesSegment(String s) {
return !s.contains("01");
}
}

• // OJ: https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/
// Time: O(N)
// Space: O(1)
class Solution {
public:
bool checkOnesSegment(string s) {
int done = false;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '1') {
if (done) return false;
} else done = true;
}
return true;
}
};

• class Solution:
def checkOnesSegment(self, s: str) -> bool:
return '01' not in s

############

# 1784. Check if Binary String Has at Most One Segment of Ones
# https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/

class Solution:
def checkOnesSegment(self, s: str) -> bool:
return "01" not in s


• func checkOnesSegment(s string) bool {
return !strings.Contains(s, "01")
}

• function checkOnesSegment(s: string): boolean {
return !s.includes('01');
}


• impl Solution {
pub fn check_ones_segment(s: String) -> bool {
!s.contains("01")
}
}