Typical... I was searching for something and accidentally landed this Leetcode problem and thought I could solve it quickly, but it wasn't to be. I wanted to use recursion and ended up muddling up and having to think about it some more. In the process, I saw various solutions from many different languages and I think the Rust solution I ended up with is much more elegantš¤£I couldn't find anywhere to post this so I decided to post it here. Maybe, it can help other Rust users attacking the problem.
It's not really a code review so to speak, but if anyone has any comments or suggestions I am happy to hear them.If there is a better category for this, let me know. I kept the function definition the same as the Leetcode definition and have longer (more descriptive) variables than I normally would...
fn main() {
// println!("{}", reverse("(ed(et(oc))el)".to_string()));
println!("{}", reverse_parentheses("The ((quick (brown) (fox) jumps over the lazy) dog)".to_string()));
}
fn reverse_parentheses(s: String) -> String {
// stop recursion and return when there are no closing brackets remaining
if !s.contains(')') {
return s.to_string();
}
let mut buf = String::new();
let mut open_bracket_indicies = Vec::new();
for (current_index, c) in s.chars().enumerate() {
match c {
'(' => open_bracket_indicies.push(current_index),
')' => {
if let Some(open_bracket_index) = open_bracket_indicies.pop() {
// build new string with inner most bracket group reversed and brackets removed for recursion
buf.push_str(&s[..open_bracket_index]);
buf.push_str(&s[open_bracket_index + 1..current_index].chars().rev().collect::<String>());
buf.push_str(&s[current_index + 1..]);
// only process first closing bracket (recursion handles the others)
break;
}
}
_ => (),
}
}
reverse_parentheses(buf)
}