1190. Reverse Substrings Between Each Pair of Parentheses
Description
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:
Example 2:
Example 3:
Example 4:
Constraints:
0 <= s.length <= 2000
s
only contains lower case English characters and parentheses.It's guaranteed that all parentheses are balanced.
Tags
Stack
Solution
The rule is that, if we meet any parenthesis, we move the pointer to the index of the corresponded parenthesis, and iterate over the input string in reverse order.
Therefore, our first step is to build the index mapping for each pair of parentheses with stack. Specifically, we build an array pair
to record the index should jump to if we meet a parenthesis. Using stack, if we find a pair of parentheses whose left and right indices are i
and j
, respectively, we do pair[i], pair[j] = j, i
.
Then, we start to perform the rule. Traverse the input string and append any non-parenthesis characters into a byte array. If we meet a parenthesis, we move i
to pair[i]
and reverse the direction of moving.
Finally, return the byte array in string
type.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?