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: , where 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划分为 ,其中 也为合法的括号组合并且是不可再分的;去除 最外层括号并连接后,作为最后的结果返回;
解法:在括号匹配的问题中我们可以利用栈来判断是否合法,同样的在这个问题中,我们可以利用栈来找到每一个最小的不可再分的 ;流程如下
- 将第一个字符添加到stack中
- 遍历字符串直到栈为空
- 遇到左括号则添加到栈中,右括号则删除栈顶的元素
- 栈空时,遍历过的字符串位置即为一个最小不可再分的
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();
}
}