leetcode_rust/
valid_parentheses.rs

1#![allow(dead_code)]
2
3// without hashmap
4pub fn is_valid(s: String) -> bool {
5    use std::collections::LinkedList;
6
7    if s.is_empty() {
8        return true;
9    }
10
11    let mut stack = LinkedList::new();
12    for ch in s.chars() {
13        match stack.back() {
14            None => stack.push_back(ch),
15            Some(&top) => {
16                if top == '(' && ch == ')' {
17                    stack.pop_back();
18                } else if top == '[' && ch == ']' {
19                    stack.pop_back();
20                } else if top == '{' && ch == '}' {
21                    stack.pop_back();
22                } else {
23                    stack.push_back(ch);
24                }
25            }
26        }
27    }
28
29    stack.is_empty()
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn test1() {
38        let s = String::from("()[]{}");
39        assert_eq!(is_valid(s), true);
40        let s = String::from("([)]");
41        assert_eq!(is_valid(s), false);
42        let s = String::from("{[]}");
43        assert_eq!(is_valid(s), true);
44    }
45}