rustgym/leetcode/
_20_valid_parentheses.rs

1struct Solution;
2
3impl Solution {
4    fn is_valid(s: String) -> bool {
5        let mut stack: Vec<char> = vec![];
6        for c in s.chars() {
7            match c {
8                '(' | '[' | '{' => stack.push(c),
9                ')' | ']' | '}' => match stack.pop() {
10                    Some(t) => {
11                        if !((t == '{' && c == '}')
12                            || (t == '(' && c == ')')
13                            || (t == '[' && c == ']'))
14                        {
15                            return false;
16                        }
17                    }
18                    None => {
19                        return false;
20                    }
21                },
22                _ => {}
23            }
24        }
25        stack.is_empty()
26    }
27}
28
29#[test]
30fn test() {
31    assert_eq!(Solution::is_valid(String::from("()")), true);
32    assert_eq!(Solution::is_valid(String::from("()[]{}")), true);
33    assert_eq!(Solution::is_valid(String::from("(]")), false);
34    assert_eq!(Solution::is_valid(String::from("([)]")), false);
35    assert_eq!(Solution::is_valid(String::from("{[]}")), true);
36}