-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parentheses.rs
More file actions
36 lines (31 loc) · 1004 Bytes
/
valid_parentheses.rs
File metadata and controls
36 lines (31 loc) · 1004 Bytes
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
use std::{char, collections::HashMap};
pub struct Solution;
impl Solution {
// Approach 1 - Brute Force
pub fn is_valid_brute_force(s: String) -> bool {
let mut s = s;
while s.contains("()") || s.contains("[]") || s.contains("{}") {
s = s.replace("()", "");
s = s.replace("[]", "");
s = s.replace("{}", "");
}
s.len() == 0
}
// Approach 2 - Stack
pub fn is_valid(s: String) -> bool {
let mut stack: Vec<char> = Vec::new();
let map: HashMap<char, char> = HashMap::from([(')', '('), (']', '['), ('}', '{')]);
for ch in s.chars().into_iter() {
if map.contains_key(&ch) {
if stack.len() > 0 && stack.last().unwrap() == map.get(&ch).unwrap() {
stack.pop();
} else {
return false;
}
} else {
stack.push(ch);
}
}
stack.len() == 0
}
}