-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_parentheses.rs
50 lines (46 loc) · 1.37 KB
/
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
42
43
44
45
46
47
48
49
50
#[allow(dead_code)]
pub fn is_valid(s: String) -> bool {
let mut stack = Vec::new();
for c in s.chars() {
match c {
'(' | '[' | '{' => stack.push(c),
')' => {
if stack.pop() != Some('(') {
return false;
}
}
']' => {
if stack.pop() != Some('[') {
return false;
}
}
'}' => {
if stack.pop() != Some('{') {
return false;
}
}
_ => unreachable!(),
}
}
stack.is_empty()
}
/*
Algorithm: Using a stack
- Create a stack
- Iterate through the string
- If the character is an opening bracket, push it onto the stack
- If the character is a closing bracket, pop the stack and compare the popped character with the current character
- If the popped character is not the corresponding opening bracket, return false
- If the stack is empty, return true
- Else, return false
Time: O(n)
Space: O(n)
*/
#[test]
fn test_is_valid() {
assert_eq!(is_valid("()".to_string()), true);
assert_eq!(is_valid("()[]{}".to_string()), true);
assert_eq!(is_valid("(]".to_string()), false);
assert_eq!(is_valid("([)]".to_string()), false);
assert_eq!(is_valid("{[]}".to_string()), true);
}