Longest Valid Parentheses in Rust

impl Solution {
    fn longest_valid_parentheses(s: String) -> i32 {
        let mut stack: Vec<isize> = vec![-1]; // Initialize a stack with -1 to handle edge cases
        let mut max_length = 0;

        for (i, char) in s.chars().enumerate() {
            if char == '(' {
                // Push the index of '(' onto the stack
                stack.push(i as isize);
            } else {
                // Pop from the stack when encountering ')'
                stack.pop();

                if stack.is_empty() {
                    // If the stack is empty, push the current index
                    stack.push(i as isize);
                } else {
                    // Calculate the length of the current valid substring
                    let current_length = i as isize - stack.last().unwrap();
                    max_length = max_length.max(current_length as usize);
                }
            }
        }

        max_length as i32
    }
}

Next