Skip to main content
Back to problems
#1190
Medium Algorithms

Reverse substrings between each pair of parentheses

String Stack
71.9% acceptance
Feb 25, 2026
2940
129
You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn reverse_parentheses(s: String) -> String {
    let mut stack: Vec<Vec<u8>> = vec![vec![]];
    for c in s.bytes() {
      match c {
        b'(' => stack.push(vec![]),
        b')' => {
          let mut top = stack.pop().unwrap();
          top.reverse();
          stack.last_mut().unwrap().extend_from_slice(&top);
        }
        ch => stack.last_mut().unwrap().push(ch),
      }
    }
    String::from_utf8(stack.pop().unwrap()).unwrap()
  }
}