Skip to content

Instantly share code, notes, and snippets.

@evanxg852000
Created February 2, 2019 17:57
Show Gist options
  • Save evanxg852000/0a3781be42231241e7b300ada509758f to your computer and use it in GitHub Desktop.
Save evanxg852000/0a3781be42231241e7b300ada509758f to your computer and use it in GitHub Desktop.
pub fn balance<T: Into<String>>(input: T) -> bool {
let mut stk = Vec::new();
for c in input.into().chars(){
match c {
a @ '(' | a @ '{' |a @ '[' => {
stk.push(a);
},
a @ ')' |a @ '}' |a @ ']' => {
match stk.pop() {
Some(t) => {
if a == ')' && t != '(' { return false;}
if a == '}' && t != '{' { return false;}
if a == ']' && t != '[' { return false;}
},
None => return false,
}
},
_ => (),
}
}
stk.len() == 0
}
fn main() {
assert_eq!(balance("()"), true);
assert_eq!(balance("("), false);
assert_eq!(balance("([])"), true);
assert_eq!(balance("([{]})"), false);
assert_eq!(balance("("), false);
assert_eq!(balance("{([])}()"), true);
println!("TEST PASSED")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment