How to check if a string contains only valid parentheses (open close same type (), {}, []) in Rust

1 Answer

0 votes
fn string_contains_valid_parentheses(s: &str) -> bool {
    let mut vec: Vec<char> = Vec::new();

    for ch in s.chars() {
        match ch {
            '(' => vec.push(')'),
            '{' => vec.push('}'),
            '[' => vec.push(']'),
            ')' | '}' | ']' => {
                if vec.is_empty() || vec.pop().unwrap() != ch {
                    return false;
                }
            }
            _ => {}
        }
    }

    // Return true if the vec is empty, indicating valid parentheses
    vec.is_empty()
}

fn main() {
    println!("{}", string_contains_valid_parentheses("(){}[]"));      
    println!("{}", string_contains_valid_parentheses("([{}])"));      
    println!("{}", string_contains_valid_parentheses("(){}[]()(){}"));
    println!("{}", string_contains_valid_parentheses("(]"));          
    println!("{}", string_contains_valid_parentheses("({[)]}"));      
}



/*
run:

true
true
true
false
false

*/

 



answered Apr 25 by avibootz
...