-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalid_parentheses.rs
98 lines (87 loc) · 2.51 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use crate::stack::Stack;
/// Given a string `s` containing just the characters '(', ')', '{', '}', '['
/// and ']', determine if the input string is valid.
///
/// An input string is valid if:
/// - Open brackets must be closed by the same type of brackets.
/// - Open brackets must be closed in the correct order.
/// - Every close bracket has a corresponding open bracket of the same type.
struct Solution;
impl Solution {
pub fn is_valid(s: String) -> bool {
let mut stack = Stack::new();
let mut result = true;
for c in s.chars() {
match c {
'(' | '[' | '{' => {
stack.push(c);
}
')' | ']' | '}' => {
match stack.pop() {
Some('(') if c == ')' => {} // all good
Some('[') if c == ']' => {} // all good
Some('{') if c == '}' => {} // all good
_ => {
// No character, or not the right match
result = false;
break;
}
}
}
_ => {
// Unexpected character
result = false;
break;
}
}
}
// If still good, verify that the stack is empty
result && stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn example_1() {
let s = "()".to_string();
let result = Solution::is_valid(s);
assert!(result);
}
#[test]
fn example_2() {
let s = "()[]{}".to_string();
let result = Solution::is_valid(s);
assert!(result);
}
#[test]
fn example_3() {
let s = "(]".to_string();
let result = Solution::is_valid(s);
assert!(!result);
}
#[test]
fn nested() {
let s = "([{}])".to_string();
let result = Solution::is_valid(s);
assert!(result);
}
#[test]
fn same_matched() {
let s = "{{{{{}}}}}".to_string();
let result = Solution::is_valid(s);
assert!(result);
}
#[test]
fn same_unmatched_open() {
let s = "{{{{{}}}}".to_string();
let result = Solution::is_valid(s);
assert!(!result);
}
#[test]
fn same_unmatched_close() {
let s = "{{{{}}}}}".to_string();
let result = Solution::is_valid(s);
assert!(!result);
}
}