Skip to content

Instantly share code, notes, and snippets.

@t-eckert
Created April 27, 2021 22:30
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 t-eckert/e3c70d5cc7aec8f927fa11b94ea986d2 to your computer and use it in GitHub Desktop.
Save t-eckert/e3c70d5cc7aec8f927fa11b94ea986d2 to your computer and use it in GitHub Desktop.
Solution to the Rotate Brackets problem in Rust
/// # 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