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 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'.
Solutions
This function validates that all 1s in a binary string are consecutive by tracking the index of the last seen 1 and checking if the current 1 is adjacent to it (distance of 1). If a 1 is found more than one position away from the previous 1, there's a gap indicating multiple segments, so it returns false. Otherwise, it returns true, confirming that all 1s form a single contiguous block.
Language: javascript(2026-03-06 09:44)DONE
CPU Performance17.71%
Memory Performance31.25%
/**
* @param {string} s
* @return {boolean}
*/
var checkOnesSegment = function(s) {
let lastOne = -1;
for (let i = 0; i < s.length; i++) {
if (s[i] === '1') {
if (lastOne > -1 && i - lastOne > 1) {
return false;
}
lastOne = i;
}
}
return true;
};