-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
70 lines (60 loc) · 1.54 KB
/
lib.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
struct Solution {}
impl Solution {
pub fn is_valid(s: String) -> bool {
let mut open_parentheses = vec![];
// itrate over string
for c in s.chars() {
match c {
'(' | '[' | '{' => open_parentheses.push(c),
')' | ']' | '}' => match open_parentheses.pop() {
Some(p) => {
if !Self::is_close_by(p, c) {
return false;
}
}
None => return false,
},
_ => (),
}
}
open_parentheses.is_empty()
}
fn is_close_by(p: char, other: char) -> bool {
match p {
'(' if other == ')' => true,
'[' if other == ']' => true,
'{' if other == '}' => true,
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_1() {
assert_eq!(Solution::is_valid("()".to_string()), true);
}
#[test]
fn case_2() {
assert_eq!(Solution::is_valid("()[]{}".to_string()), true);
}
#[test]
fn case_3() {
assert_eq!(Solution::is_valid("(]".to_string()), false);
}
#[test]
fn case_4() {
assert_eq!(
Solution::is_valid("((([[[{{{(({({[]})}))}}}]]])))".to_string()),
true
);
}
#[test]
fn case_5() {
assert_eq!(
Solution::is_valid("((([[[{{{(({({[]})}))}}}]])))".to_string()),
false
);
}
}