【栈】B016_LC_反转每对括号间的子串(栈记录左括号 + 局部翻转)

一、Problem

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.

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

Constraints:

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

二、Solution

方法一:栈记录左括号

class Solution {
    void reverse(char[] s, int l, int r) {
        while (l < r) {
            char c = s[l];
            s[l++] = s[r];
            s[r--] = c;
        }
    }
    public String reverseParentheses(String S) {
        char[] s = S.toCharArray();
        Stack<Integer> st = new Stack<>();

        for (int i = 0; i < s.length; i++) {
            if (s[i] == '(')
                st.push(i);
            else if (s[i] == ')') {
                reverse(s, st.pop()+1, i-1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length; i++) if (Character.isLetter(s[i])) {
            sb.append(s[i]);
        }
        return sb.toString();
    }
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/106907316