1190. Reverse Substrings Between Each Pair of Parentheses

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.

 

Example 1:

Input: s = "(abcd)"
Output: "dcba"

Example 2:

Input: s = "(u(love)i)"
Output: "iloveu"
Explanation: The substring "love" is reversed first, then the whole string is reversed.

Example 3:

Input: s = "(ed(et(oc))el)"
Output: "leetcode"
Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.

Example 4:

Input: s = "a(bcdefghijkl(mno)p)q"
Output: "apmnolkjihgfedcbq"

 

Constraints:

  • 0 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It's guaranteed that all parentheses are balanced.

Rust Solution

struct Solution;

use std::collections::VecDeque;

impl Solution {
    fn reverse_parentheses(s: String) -> String {
        let mut stack: Vec<char> = vec![];
        let mut queue: VecDeque<char> = VecDeque::new();
        for c in s.chars() {
            if c == ')' {
                while let Some(top) = stack.pop() {
                    if top == '(' {
                        while let Some(front) = queue.pop_front() {
                            stack.push(front);
                        }
                        break;
                    } else {
                        queue.push_back(top);
                    }
                }
            } else {
                stack.push(c);
            }
        }
        stack.iter().collect()
    }
}

#[test]
fn test() {
    let s = "(abcd)".to_string();
    let res = "dcba".to_string();
    assert_eq!(Solution::reverse_parentheses(s), res);
    let s = "(u(love)i)".to_string();
    let res = "iloveu".to_string();
    assert_eq!(Solution::reverse_parentheses(s), res);
    let s = "(ed(et(oc))el)".to_string();
    let res = "leetcode".to_string();
    assert_eq!(Solution::reverse_parentheses(s), res);
    let s = "a(bcdefghijkl(mno)p)q".to_string();
    let res = "apmnolkjihgfedcbq".to_string();
    assert_eq!(Solution::reverse_parentheses(s), res);
}

Having problems with this solution? Click here to submit an issue on github.