LeetCode-Remove Outermost Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89086438

Description:
A valid parentheses string is either empty (""), “(” + A + “)”, or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, “”, “()”, “(())()”, and “(()(()))” are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: S = P 1 + P 2 + . . . + P k S = P_1 + P_2 + ... + P_k , where P i P_i are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

Example 1:

Input: "(()())(())"
Output: "()()()"
Explanation: 
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".

Example 2:

Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation: 
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".

Example 3:

Input: "()()"
Output: ""
Explanation: 
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".

Note:

  • S.length <= 10000
  • S[i] is “(” or “)”
  • S is a valid parentheses string

题意:给定一个字符串S为一个合法的括号组合,将S划分为 S = P 1 + P 2 + . . . + P k S = P_1 + P_2 + ... + P_k ,其中 P 1 , P 2 , . . . , P k P_1,P_2,..., P_k 也为合法的括号组合并且是不可再分的;去除 P 1 , P 2 , . . . , P k P_1,P_2,..., P_k 最外层括号并连接后,作为最后的结果返回;

解法:在括号匹配的问题中我们可以利用栈来判断是否合法,同样的在这个问题中,我们可以利用栈来找到每一个最小的不可再分的 P 1 , P 2 , . . . , P k P_1,P_2,..., P_k ;流程如下

  1. 将第一个字符添加到stack中
  2. 遍历字符串直到栈为空
  3. 遇到左括号则添加到栈中,右括号则删除栈顶的元素
  4. 栈空时,遍历过的字符串位置即为一个最小不可再分的 P 1 , P 2 , . . . , P k P_1,P_2,..., P_k
Java
class Solution {
    public String removeOuterParentheses(String S) {
        StringBuilder res = new StringBuilder();
        LinkedList<Character> stack = new LinkedList<>();
        for (int st = 0, ed = 0; ed != S.length();) {
            st = ed;
            stack.addLast(S.charAt(ed));
            ed++;
            while (stack.size() != 0 && ed != S.length()) {
                char ch = S.charAt(ed);
                if (ch == '(') {
                    stack.addLast(ch);
                } else {
                    stack.pollLast();
                }
                ed++;
            }
            res.append(S.substring(st + 1, ed - 1));
        }
        
        return res.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/89086438