[LeetCode] Longer Contiguous Segments of Ones than Zeros

1869. Longer Contiguous Segments of Ones than Zeros

Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise.

  • For example, in s = “110100010” the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3.

Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool checkZeroOnes(string s) {
int zero(s[0] == '0'), one(s[0]=='1');
int mz = zero, mo = one;
for(int i = 1; i < s.length(); i++) {
if(s[i] == '1') {
if(s[i - 1] == '0') one = 0;
one++;
} else {
if(s[i - 1] == '1') zero = 0;
zero++;
}
mz = max(mz, zero);
mo = max(mo, one);
}
return mo > mz;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/23/PS/LeetCode/longer-contiguous-segments-of-ones-than-zeros/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.