carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1869: Longer Contiguous Segments of Ones than Zeros #299

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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.

For example, in s = "110100010" 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.

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

carloscn commented 1 year ago

Analysis

pub fn check_zero_ones(s: &str) -> bool
{
    if s.len() < 1 {
        return false;
    }

    let s_v:Vec<char> = s.chars().collect();
    let (mut one_count, mut zero_count,
         mut max_one_count, mut max_zero_count) =
        (0usize, 0usize, usize::MIN, usize::MIN);

    for i in 0..s_v.len() - 1 {
        if s_v[i] == s_v[i + 1] && s_v[i] == '1' {
            one_count += 1;
            max_one_count = one_count.max(max_one_count);
        } else if s_v[i] == s_v[i + 1] && s_v[i] == '0' {
            zero_count += 1;
            max_zero_count = zero_count.max(max_zero_count);
        } else if s_v[i] != s_v[i + 1] {
            one_count = 0;
            zero_count = 0;
        }
    }

    return max_one_count > max_zero_count;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/557399 https://github.com/carloscn/structstudy/commit/48c4f267f9aed4ed96646ade155ed365f4a74933