Created
April 27, 2021 22:30
-
-
Save t-eckert/e3c70d5cc7aec8f927fa11b94ea986d2 to your computer and use it in GitHub Desktop.
Solution to the Rotate Brackets problem in Rust
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
/// # Rotate Brackets | |
/// | |
/// Given a string of brackets, return a rotation of those brackets that is balanced. | |
/// The numbers of opening and closing brackets will always be equal. | |
/// | |
/// Example | |
/// ``` | |
/// rotate_brackets("]][][["); | |
/// "[[]][]" // First rotation yields "[]][][". Second one yields "[[]][]" | |
/// ``` | |
/// | |
/// So we have to rotate and check until we have reached balance. | |
fn main() { | |
let brackets = String::from("]][][["); | |
let rotated_brackets = rotate_brackets(brackets); | |
println!("{}", rotated_brackets); | |
} | |
/// Takes a string of brackets (`[`,`]`) and rotates that string (first element | |
/// becomes last and other elements shift towards the front of the list by 1) | |
/// until that string has a right bracket matching every left bracket, for example, | |
/// `[[]][]`. | |
fn rotate_brackets(brackets: String) -> String { | |
let rotated_string = rotate_string(brackets); | |
if !is_balanced(&rotated_string) { | |
return rotate_brackets(rotated_string); | |
} | |
return rotated_string | |
} | |
/// Takes a string and rotates that string, making the first element last and | |
/// shifting all other elements towards the front of the string by 1. | |
/// rotate_string("Hello") // returns "elloH" | |
fn rotate_string(string: String) -> String { | |
let mut characters: Vec<char> = string.chars().collect(); | |
characters.rotate_right(1); | |
characters.iter().collect() | |
} | |
/// Checks that every left bracket has a matching right bracket to "close" it | |
/// is_balanced("[[]]") // returns true | |
/// is_balanced("][") // returns false | |
fn is_balanced(string: &String) -> bool { | |
let mut left_brackets = 0; | |
for bracket in string.chars() { | |
match bracket { | |
'[' => left_brackets = left_brackets + 1, | |
']' => left_brackets = left_brackets - 1, | |
_ => (), | |
}; | |
if left_brackets < 0 { | |
return false; | |
} | |
} | |
true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment