Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 65865d7

Browse files
committedJun 2, 2023
feat: add valid parentheses
1 parent e332510 commit 65865d7

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
 

‎src/easy/valid_parentheses.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#[allow(dead_code)]
2+
pub fn is_valid(s: String) -> bool {
3+
let mut stack = Vec::new();
4+
for c in s.chars() {
5+
match c {
6+
'(' | '[' | '{' => stack.push(c),
7+
')' => {
8+
if stack.pop() != Some('(') {
9+
return false;
10+
}
11+
}
12+
']' => {
13+
if stack.pop() != Some('[') {
14+
return false;
15+
}
16+
}
17+
'}' => {
18+
if stack.pop() != Some('{') {
19+
return false;
20+
}
21+
}
22+
_ => unreachable!(),
23+
}
24+
}
25+
stack.is_empty()
26+
}
27+
28+
/*
29+
30+
*/
31+
32+
#[test]
33+
fn test_is_valid() {
34+
assert_eq!(is_valid("()".to_string()), true);
35+
assert_eq!(is_valid("()[]{}".to_string()), true);
36+
assert_eq!(is_valid("(]".to_string()), false);
37+
assert_eq!(is_valid("([)]".to_string()), false);
38+
assert_eq!(is_valid("{[]}".to_string()), true);
39+
}

0 commit comments

Comments
 (0)