Skip to content

Instantly share code, notes, and snippets.

@rafaelrcamargo
Created April 22, 2024 14:36
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 rafaelrcamargo/e128219ef796c15a2c08c4970dfe607e to your computer and use it in GitHub Desktop.
Save rafaelrcamargo/e128219ef796c15a2c08c4970dfe607e to your computer and use it in GitHub Desktop.
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,
})
}
@rafaelrcamargo
Copy link
Author

Tests:

#[cfg(test)]
mod tests {
    #[test]
    fn test_is_balanced() {
        assert_eq!(super::is_balanced("abcd"), true);
        assert_eq!(super::is_balanced("(abcd)"), true);
        assert_eq!(super::is_balanced("(abcd"), false);
        assert_eq!(super::is_balanced("abcd]"), false);
        assert_eq!(super::is_balanced("(abc)d"), true);
        assert_eq!(super::is_balanced("(abc]d"), false);
        assert_eq!(super::is_balanced("(abc[%def])"), true);
        assert_eq!(super::is_balanced("$(abc[de]fg{hi}jk)%//"), true);
        assert_eq!(super::is_balanced("(({abc})"), false);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment