Browse Source

Only 3 pairs, move away from HashSet

master
Jim Infield 3 years ago
parent
commit
c4989cf118
  1. 14
      src/lib.rs

14
src/lib.rs

@ -1,21 +1,13 @@
pub fn brackets_are_balanced(string: &str) -> bool { pub fn brackets_are_balanced(string: &str) -> bool {
use std::collections::HashMap;
let pairs: HashMap<char, char> = [(')', '('), ('}', '{'), (']', '[')]
.iter().cloned().collect();
let mut stack = vec![]; let mut stack = vec![];
for char in string.chars() { for char in string.chars() {
match char { match char {
'(' | '{' | '[' => stack.push(char), '(' | '{' | '[' => stack.push(char),
')' | '}' | ']' => {
if let Some(left) = stack.pop() {
if let Some(right) = pairs.get(&char) {
if left != *right { return false }
}
} else { return false }
},
')' => if stack.pop() != Some('(') { return false },
'}' => if stack.pop() != Some('{') { return false },
']' => if stack.pop() != Some('[') { return false },
_ => {}, _ => {},
} }
} }

Loading…
Cancel
Save