Skip to content

Instantly share code, notes, and snippets.

@spazm
Last active April 30, 2019 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spazm/1784420d8efbc3d88bddc7efc8a57b81 to your computer and use it in GitHub Desktop.
Save spazm/1784420d8efbc3d88bddc7efc8a57b81 to your computer and use it in GitHub Desktop.
matching brackets rust code. Attempt #2
pub fn brackets_are_balanced(string: &str) -> bool {
// second attempt/idea:
// push opening brace onto array
// pop array on close and check for match
// pop on empty => false
// not empty at end => false
// third attempt:
// make a hashmap of open/close remove code duplication in the
// close bracket logic
// Is this really the best way to make a fixed hashmap? Also, we
// build it everytime.
let mut found = Vec::new();
// create a hashmap from a fixed list of of open/close pairs
// Map{close}=open
let opening_bracket: std::collections::HashMap<char, char> =
[('[', ']'), ('{', '}'), ('(', ')')]
.iter()
.cloned()
.map(|(a, b)| (b, a))
.collect();
// println!("{:?}", opening_bracket);
for c in string.chars() {
match c {
'{' | '(' | '[' => found.push(c),
'}' | ')' | ']' => match (found.pop(), opening_bracket.get(&c)) {
(Some(open), Some(&exp_open)) => {
if open != exp_open {
return false;
}
}
(_, _) => return false,
},
_ => (),
}
}
found.is_empty()
}
pub fn brackets_are_balanced(string: &str) -> bool {
// second attempt/idea:
// push opening brace onto array
// pop array on close and check for match
// pop on empty => false
// not empty at end => false
let mut found = Vec::new();
for c in string.chars() {
match c {
'{' | '(' | '[' => found.push(c),
']' => match found.pop() {
Some('[') => (),
_ => return false,
},
')' => match found.pop() {
Some('(') => (),
_ => return false,
},
'}' => match found.pop() {
Some('{') => (),
_ => return false,
},
_ => (),
}
}
found.is_empty()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment