Remove Outermost Parentheses
用一个count来计算”(“和”)”的差,0就是最外边的。
class Solution {
public String removeOuterParentheses(String S) {
int count = 0; // count the diff between "(" and ")"
StringBuffer res = new StringBuffer();
StringBuffer tmp = new StringBuffer();
for(int i = 0 ; i < S.length(); i++) {
if(S.charAt(i) == '(')
count++;
else if(S.charAt(i) == ')')
count--;
tmp.append(S.charAt(i));
if(count == 0){ // if it is outter
tmp.deleteCharAt(0); // remove first
tmp.deleteCharAt(tmp.length()-1);//remove last
res.append(tmp);
tmp.setLength(0); //reset tmp
}
}
return res.toString();
}
}