思路
用一个count变量对"("计数,每入一个新的"("count加1,每入一个新的")"count减1。
因为去除的是最外层括号,所以在count为0时不保存左括号,count为1时不保存右括号。
class Solution {
public String removeOuterParentheses(String S) {
char[] chs = S.toCharArray();
StringBuffer result = new StringBuffer();
int count = 0;
for(int i=0; i<chs.length; i++) {
if (chs[i] == '(') {
if (count>=1)
result.append('(');
count ++;
} else {
if (count>1)
result.append(')');
count --;
}
}
return result.toString();
}
}
注意:拼接字符串的结果result不要用String对象,如果使用String,则每次拼接都要新生成一个String对象,导致生成大量对象,造成空间浪费以及消耗额外的时间。使用StringBuffer则在原有对象基础上进行修改,可以节省不少时间。
# String result
result += '(';
# StringBuffer result
result.append('(');