Given a binary string s, return true _if thelongest contiguous segment of _1’_s isstrictly longer than the longest contiguous segment of _0’s ins, or return falseotherwise.
For example, in s = "_11_ 01 _000_ 10" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s 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.
Input: s ="1101"Output: trueExplanation:
The longest contiguous segment of 1s has length 2:"_11_ 01"The longest contiguous segment of 0s has length 1:"11 _0_ 1"The segment of 1s is longer, so returntrue.
Input: s ="111000"Output: falseExplanation:
The longest contiguous segment of 1s has length 3:"_111_ 000"The longest contiguous segment of 0s has length 3:"111 _000_ "The segment of 1s is not longer, so returnfalse.
Input: s ="110100010"Output: falseExplanation:
The longest contiguous segment of 1s has length 2:"_11_ 0100010"The longest contiguous segment of 0s has length 3:"1101 _000_ 10"The segment of 1s is not longer, so returnfalse.
We can find the longest contiguous segment of ‘1’s and ‘0’s by scanning the string once and keeping track of the current and maximum segment lengths for both characters.
classSolution {
publicbooleancheckZeroOnes(String s) {
int max1 = 0, max0 = 0, cur = 1;
for (int i = 1; i <= s.length(); i++) {
if (i < s.length() && s.charAt(i) == s.charAt(i-1)) cur++;
else {
if (s.charAt(i-1) =='1') max1 = Math.max(max1, cur);
else max0 = Math.max(max0, cur);
cur = 1;
}
}
return max1 > max0;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funcheckZeroOnes(s: String): Boolean {
var max1 = 0; var max0 = 0; var cur = 1for (i in1..s.length) {
if (i < s.length && s[i] == s[i-1]) cur++else {
if (s[i-1] =='1') max1 = maxOf(max1, cur)
else max0 = maxOf(max0, cur)
cur = 1 }
}
return max1 > max0
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcheckZeroOnes(self, s: str) -> bool:
max1 = max0 = cur =1for i in range(1, len(s)+1):
if i < len(s) and s[i] == s[i-1]:
cur +=1else:
if s[i-1] =='1':
max1 = max(max1, cur)
else:
max0 = max(max0, cur)
cur =1return max1 > max0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfncheck_zero_ones(s: String) -> bool {
let s = s.as_bytes();
let (mut max1, mut max0, mut cur) = (0, 0, 1);
for i in1..=s.len() {
if i < s.len() && s[i] == s[i-1] {
cur +=1;
} else {
if s[i-1] ==b'1' {
max1 = max1.max(cur);
} else {
max0 = max0.max(cur);
}
cur =1;
}
}
max1 > max0
}
}