1078. Remove Outermost Parentheses
2026/1/12大约 2 分钟约 489 字
1078. Remove Outermost Parentheses
难度: Easy
题目描述
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 = P1 + P2 + ... + Pk, where Pi 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: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: s = "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: s = "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "".
Constraints:
1 <= s.length <= 105s[i]is either'('or')'.sis a valid parentheses string.
解题思路
代码实现
解决方案
java
class Solution {
public String removeOuterParentheses(String s) {
char[] cArray = s.toCharArray();
ArrayList<Character> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int leftCount=0;
int rightCount=0;
for (char c : cArray) {
switch (c) {
case '(':
list.add('(');
leftCount++;
break;
case ')':
list.add(')');
rightCount++;
if(leftCount==rightCount){
if(list.size()>2){
for(int i=1;i<list.size()-1;i++){
sb.append(list.get(i));
}
}
leftCount=0;
rightCount=0;
list.clear();
}
break;
}
}
return sb.toString();
}
}