Remove Outermost Parentheses
用一个count来计算”(“和”)”的差,0就是最外边的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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(); } } |