Last active
April 30, 2019 01:01
-
-
Save spazm/1784420d8efbc3d88bddc7efc8a57b81 to your computer and use it in GitHub Desktop.
matching brackets rust code. Attempt #2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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