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