-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0020_valid_parentheses.rs
More file actions
41 lines (37 loc) · 1.09 KB
/
s0020_valid_parentheses.rs
File metadata and controls
41 lines (37 loc) · 1.09 KB
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
#![allow(unused)]
pub struct Solution {}
impl Solution {
// O(n) O(n)
pub fn is_valid(s: String) -> bool {
let mut stack = vec![];
for ch in s.chars() {
if ch == '(' || ch == '{' || ch == '[' {
stack.push(ch);
} else {
if let Some(c) = stack.pop() {
if (ch == ')' && c == '(') || (ch == '}' && c == '{') || (ch == ']' && c == '[')
{
continue;
} else {
return false;
}
} else {
return false;
}
}
}
stack.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_20() {
assert_eq!(Solution::is_valid("()".to_owned()), true);
assert_eq!(Solution::is_valid("()[]{}".to_owned()), true);
assert_eq!(Solution::is_valid("{()}".to_owned()), true);
assert_eq!(Solution::is_valid("([)]".to_owned()), false);
assert_eq!(Solution::is_valid("(]".to_owned()), false);
}
}