原先没有思路,可以看看leetcode上的提示
class Solution {
public String removeOuterParentheses(String S) {
StringBuilder res = new StringBuilder();
//定义两个变量记录左括号数量与右括号数量
int leftcount = 0, rightcount = 0;
for(int i=0; i<S.length(); i++){
//取出字符串中的每一个字符
char ch = S.charAt(i);
//当字符为左括号时,计数
//如果leftcount == rightcount+1不做处理
//否则,添加进res中
if(ch == '('){
leftcount ++;
if(leftcount == rightcount+1) continue;
else {
res.append(ch);
}
}
//当字符为右括号时,计数
//如果leftcount == rightcount不做处理
//否则,添加进res中
if(ch == ')'){
rightcount ++;
if(leftcount == rightcount) continue;
else{
res.append(ch);
}
}
}
return res.toString();
}
}