[LeetCode] 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.

反转每对括号间的子串。

给出一个字符串 s(仅含有小写英文字母和括号)。

请你按照从括号内到外的顺序,逐层反转每对匹配括号中的字符串,并返回最终的结果。

注意,您的结果中 不应 包含任何括号。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-substrings-between-each-pair-of-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

既然是每次遇到括号就需要反转括号内的东西,那么思路是用到stack。我们按char遍历input字符串,

如果当前是左括号,则创建一个新的StringBuilder存放括号内的子串

如果当前是右括号,说明要开始reverse这一部分的内容了,则我们把这一部分从stack中弹出,reverse,再append到此时栈顶那个StringBuilder;也就是说每一部分完成反转之后,需要被append到之前的子串上

如果当前是char,则append到栈顶那个StringBuilder上

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public String reverseParentheses(String s) {
 3         StringBuilder sb = new StringBuilder();
 4         Stack<StringBuilder> stack = new Stack<>();
 5         stack.push(new StringBuilder());
 6         for (char c : s.toCharArray()) {
 7             if (c == '(') {
 8                 stack.push(new StringBuilder());
 9             } else if (c == ')') {
10                 StringBuilder top = stack.pop();
11                 stack.peek().append(top.reverse());
12             } else {
13                 stack.peek().append(c);
14             }
15         }
16         return stack.pop().toString();
17     }
18 }

 

JavaScript实现

 1 /**
 2  * @param {string} s
 3  * @return {string}
 4  */
 5 var reverseParentheses = function (s) {
 6     let stack = [];
 7     stack.push('');
 8     for (let c of s) {
 9         if (c == '(') {
10             stack.push('');
11         } else if (c == ')') {
12             let top = stack.pop();
13             stack[stack.length - 1] += top.split('').reverse().join('');
14         } else {
15             stack[stack.length - 1] += c;
16         }
17     }
18     return stack.pop();
19 };

 

LeetCode 题目总结

posted @ 2021-02-05 16:53  CNoodle  阅读(127)  评论(0编辑  收藏  举报