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.

 

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'.

1869. Longer Contiguous Segments of Ones than Zeros
struct Solution;

impl Solution {
    fn check_zero_ones(s: String) -> bool {
        let s: Vec<char> = s.chars().collect();
        let n = s.len();
        let mut state = '2';
        let mut length = 0;
        let mut zero = 0;
        let mut one = 0;
        for i in 0..n {
            if s[i] == state {
                length += 1;
            } else {
                state = s[i];
                length = 1;
            }
            if s[i] == '0' {
                zero = zero.max(length);
            } else {
                one = one.max(length);
            }
        }
        one > zero
    }
}

#[test]
fn test() {
    let s = "1101".to_string();
    let res = true;
    assert_eq!(Solution::check_zero_ones(s), res);
    let s = "111000".to_string();
    let res = false;
    assert_eq!(Solution::check_zero_ones(s), res);
    let s = "110100010".to_string();
    let res = false;
    assert_eq!(Solution::check_zero_ones(s), res);
}