Given a binary string s
, return true
if the longest contiguous segment of 1
's is strictly longer than the longest contiguous segment of 0
's in s
, or return false
otherwise.
s = "110100010"
the longest continuous segment of 1
s has length 2
, and the longest continuous segment of 0
s has length 3
.Note that if there are no 0
's, then the longest continuous segment of 0
's is considered to have a length 0
. The same applies if there is no 1
's.
Example 1:
Input: s = "1101" Output: true Explanation: The longest contiguous segment of 1s has length 2: "1101" The longest contiguous segment of 0s has length 1: "1101" The segment of 1s is longer, so return true.
Example 2:
Input: s = "111000" Output: false Explanation: The longest contiguous segment of 1s has length 3: "111000" The longest contiguous segment of 0s has length 3: "111000" The segment of 1s is not longer, so return false.
Example 3:
Input: s = "110100010" Output: false Explanation: The longest contiguous segment of 1s has length 2: "110100010" The longest contiguous segment of 0s has length 3: "110100010" The segment of 1s is not longer, so return false.
Constraints:
1 <= s.length <= 100
s[i]
is either '0'
or '1'
.This problem asks to determine if the longest contiguous segment of '1's in a binary string is strictly longer than the longest contiguous segment of '0's.
Approach:
The most efficient approach involves two linear scans of the input string. We can create a helper function f(x)
that takes a character ('0' or '1') and returns the length of the longest contiguous segment of that character in the input string. Then, we simply compare f('1')
and f('0')
. If f('1')
is greater, we return true
; otherwise, false
.
Algorithm:
Helper Function f(x)
:
cnt
(current count) and mx
(maximum count) to 0.x
, increment cnt
and update mx
to be the maximum of mx
and cnt
.cnt
to 0.mx
.Main Function:
f('1')
to get the length of the longest contiguous segment of '1's.f('0')
to get the length of the longest contiguous segment of '0's.true
if f('1') > f('0')
, otherwise false
.Time and Space Complexity:
cnt
and mx
.Code Implementation (Python):
class Solution:
def checkZeroOnes(self, s: str) -> bool:
def f(x: str) -> int:
cnt = mx = 0
for c in s:
if c == x:
cnt += 1
mx = max(mx, cnt)
else:
cnt = 0
return mx
return f("1") > f("0")
Code Implementation (Java):
class Solution {
public boolean checkZeroOnes(String s) {
return f(s, '1') > f(s, '0');
}
private int f(String s, char x) {
int cnt = 0, mx = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == x) {
mx = Math.max(mx, ++cnt);
} else {
cnt = 0;
}
}
return mx;
}
}
(Other languages like C++, Go, TypeScript, and JavaScript implementations are similar and follow the same logic. Refer to the provided code snippets for those implementations.)
This solution is efficient and straightforward, making it a good approach for solving this problem. The use of a helper function improves readability and code organization.