Browse Source

Only 3 pairs, move away from HashSet

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

16
src/lib.rs

@ -1,22 +1,14 @@
pub fn brackets_are_balanced(string: &str) -> bool {
use std::collections::HashMap;
let pairs: HashMap<char, char> = [(')', '('), ('}', '{'), (']', '[')]
.iter().cloned().collect();
let mut stack = vec![];
for char in string.chars() {
match 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 },
_ => {},
}
}
stack.is_empty()
Loading…
Cancel
Save