Valid Parentheses in Rust

impl Solution {
    fn is_valid(s: String) -> bool {
        let mut stack = Vec::new(); // Create an empty stack

        for c in s.chars() {
            match c {
                // Push the corresponding opening bracket onto the stack
                '(' | '{' | '[' => stack.push(c),
                // Check for the correct closing bracket
                ')' => {
                    if stack.pop() != Some('(') {
                        return false;
                    }
                }
                '}' => {
                    if stack.pop() != Some('{') {
                        return false;
                    }
                }
                ']' => {
                    if stack.pop() != Some('[') {
                        return false;
                    }
                }
                _ => (), // Ignore other characters
            }
        }

        // If the stack is empty, all brackets were matched correctly
        stack.is_empty()
    }
}

PrevNext