题目来源
解析描述
题目分析
解决这道题的关键在于,需要知道哪些是需要去除的外层括号,为了找到这些需要去除的外层括号,我们可以使用计数器。
规则:遇到(
,我们的计数器+1
,遇到右括号,我们的计数器-1
。
这样的话,一组连续而且有序的括号,将不会对计数器的值产生变化。
// 示例一
当前的计数值: 0 1 0 1
( ) ( )
遍历后计数值: 1 0 1 0
// 示例二
当前的计数值: 0 1 2 1 2 1 0 1
( ( ) ( ) ) ( )
遍历后计数值: 1 2 1 2 1 0 1 0
根据上述两个示例,我们可以很快的找出规律:
- 遇到左括号,当前计数值大于 0 0 0 ,则属于有效的左括号。
- 遇到右括号,当前计数值大于 1 1 1,则属于有效的右括号。
题目解析
package com.oceanstar;
public class Solution {
public static String removeOuterParentheses(String S) {
if (S.equals("")){
return "";
}
StringBuilder res = new StringBuilder();
char[] cs = S.toCharArray();
int count = 0;
for (int i = 0; i < cs.length; i++){
if (cs[i] == ')'){
count--;
}
if (count >= 1){
res.append(cs[i]);
}
if (cs[i] == '('){
count++;
}
}
return res.toString();
}
public static void main(String[] args) {
System.out.println(removeOuterParentheses("(()())(())(()(()))"));
}
}
使用栈
class Solution {
public:
string removeOuterParentheses(string s) {
std::string res;
std::stack<int> stack;
for (int i = 0; i < s.size(); ++i) {
if(s[i] == '('){
stack.push(i);
}else{
int start = stack.top(); stack.pop();
if(stack.empty()){
res += s.substr(start + 1, i - start - 1);
}
}
}
return res;
}
};