Created
April 22, 2024 14:36
-
-
Save rafaelrcamargo/e128219ef796c15a2c08c4970dfe607e to your computer and use it in GitHub Desktop.
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 is_balanced(s: &str) -> bool { | |
let mut stack = Vec::new(); | |
for c in s.chars() { | |
match c { | |
'(' | '[' | '{' => stack.push(c), | |
symbol @ (')' | ']' | '}') if stack.pop() != reverse(symbol) => return false, | |
_ => (), | |
} | |
} | |
stack.is_empty() | |
} | |
fn reverse(c: char) -> Option<char> { | |
Some(match c { | |
')' => '(', | |
']' => '[', | |
'}' => '{', | |
_ => c, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests: