commit
d9064f77df
@ -0,0 +1 @@
|
||||
target/
|
@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "balance"
|
||||
version = "0.1.0"
|
@ -0,0 +1,4 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"balance"
|
||||
]
|
@ -0,0 +1 @@
|
||||
/target
|
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "balance"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
@ -0,0 +1,48 @@
|
||||
/// 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()));
|
||||
}
|
||||
}
|
Loading…
Reference in new issue