0
点赞
收藏
分享

微信扫一扫

LeetCode 1190 Reverse Substrings Between Each Pair of Parentheses (dfs 栈 推荐)

圣杰 2022-02-04 阅读 74
leetcodedfs

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.

Constraints:

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

题目链接:https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/

题目大意:在括号内的字符串需进行一次翻转,求最终生成的字符串

题目分析:开始受到之前某题影响,一直在考虑翻转偶数次可以不翻的方法,由于本题存在同一层中嵌套翻转的情况比如(abc(de)fg(hij)xy),即使子串本身最终可能没有被翻,但其在全局的位置会发生变化,故不方便用奇偶的思路处理,于是就是个递归模拟问题了,遇到左括号则对其包含的合法子串进行递归即可

2ms,时间击败82.33%

class Solution {
    
    public String reverseParentheses(String s) {
        StringBuffer ans = new StringBuffer("");
        char[] str = s.toCharArray();
        int i = 0, n = str.length;
        while (i < n) {
            if (str[i] == '(') {
                int cnt = 1;
                i++;
                StringBuffer tmp = new StringBuffer("");
                while (i < n && cnt > 0) {
                    if (str[i] == '(') {
                        cnt++;
                    } else if (str[i] == ')') {
                        cnt--;
                    }
                    if (cnt > 0) {
                        tmp.append(str[i]);
                    }
                    i++;
                }
                ans.append(new StringBuffer(reverseParentheses(tmp.toString())).reverse());
            } else if (str[i] >= 'a' && str[i] <= 'z') {
                ans.append(str[i++]);
            }
        }
        return ans.toString();
    }
}
举报

相关推荐

0 条评论