carloscn / structstudy

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

leetcode2609: Find the Longest Balanced Substring of a Binary String #427

Open carloscn opened 12 months ago

carloscn commented 12 months ago

Description

You are given a binary string s consisting only of zeroes and ones.

A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.

Return the length of the longest balanced substring of s.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: s = "01000111" Output: 6 Explanation: The longest balanced substring is "000111", which has length 6.

Example 2:

Input: s = "00111" Output: 4 Explanation: The longest balanced substring is "0011", which has length 4.

Example 3:

Input: s = "111" Output: 0 Explanation: There is no balanced substring except the empty substring, so the answer is 0.

Constraints:

1 <= s.length <= 50 '0' <= s[i] <= '1'

carloscn commented 12 months ago

Analysis

pub fn find_the_longest_balanced_substring(s: &str) -> i32
{
    let mut ret:i32 = 0;
    if s.len() < 1 {
        return ret;
    }

    let mut c_s:Vec<char> = s.chars().collect();
    let mut count:usize = 0;
    let mut i = 0;
    // 00111
    while i < c_s.len() {
        if c_s[i] != '1' {
            i += 1;
            count = 0;
            continue;
        } else {
            if i == 0 {
                i += 1;
                continue;
            }
            let mut j: i32 = (i - 1) as i32;
            while j >= 0 && i < c_s.len() && c_s[j as usize] == '0' && c_s[i] == '1' {
                count += 1;
                j -= 1;
                i += 1;
            }
            i += 1;
        }

        ret = ret.max(count as i32);
    }

    ret *= 2;

    return ret;
}
carloscn commented 12 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1172420 https://github.com/carloscn/structstudy/commit/5e133aa396f15dcbbbff96d84503e9c16acac1a5