Created
February 20, 2023 17:10
-
-
Save wperron/2e66c31ff0e3997b2dd212c46e765073 to your computer and use it in GitHub Desktop.
balance parens
This file contains 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
/// Given a string of parenthesis, return the number of parenthesis you need to add to the string in order for it to be balanced. | |
/// | |
/// Examples: | |
/// | |
/// ```bash | |
/// > numBalanced(`()`) | |
/// > 0 | |
/// | |
/// > numBalanced(`(()`) | |
/// > 1 | |
/// | |
/// > numBalanced(`))()))))()`) | |
/// > 6 | |
/// | |
/// > numBalanced(`)))))`) | |
/// > 5 | |
/// ``` | |
fn main() { | |
println!("{}", balance("))()))))()".to_string())); | |
} | |
fn balance(s: String) -> isize { | |
let mut to_balance: isize = 0; | |
for c in s.chars() { | |
match c { | |
'(' => to_balance += 1, | |
')' => to_balance -= 1, | |
_ => unreachable!("unexpected character"), | |
} | |
} | |
to_balance.abs() | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn test_balance() { | |
assert_eq!(0, balance("()".to_string())); | |
assert_eq!(1, balance("(()".to_string())); | |
assert_eq!(6, balance("))()))))()".to_string())); | |
assert_eq!(5, balance(")))))".to_string())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment