-
Notifications
You must be signed in to change notification settings - Fork 1
/
20.valid-parentheses.rs
42 lines (37 loc) · 1014 Bytes
/
20.valid-parentheses.rs
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
/*
* @lc app=leetcode id=20 lang=rust
*
* [20] Valid Parentheses
*/
// @lc code=start
use std::collections::LinkedList;
use std::collections::HashMap;
impl Solution {
pub fn is_valid(s: String) -> bool {
let mut stack = LinkedList::new();
let mut map = HashMap::new();
map.insert(')', '(');
map.insert('}', '{');
map.insert(']', '[');
for c in s.chars() {
if (c == '(' || c == '{' || c == '[') {
stack.push_back(c);
}
else if (stack.len() > 0) {
let prev = stack.pop_back().unwrap();
match map.get(&c) {
Some(mapTo) => {
if (mapTo != &prev) {
return false;
}
},
None => return false
}
} else {
return false;
}
}
return stack.len() == 0;
}
}
// @lc code=end