题目大意: 移除最外层的多余括号。
解题大致思路: 当出现最外层括号的时候即左括号和右括号的个数相等, 所以,我们用一个字符tmp串记录下当前的子串,用cnt表示左右括号个数的和 (ps: 碰到左括号 cnt 加一 碰到右括号 cnt 减一) 当cnt = 0 的时候 左括号和右括号相等。 去除掉 tmp的头尾 即是我们当前所求的结果 。清除tmp 。以此重复到字符串结束。ans get !! !
一下是我的代码:
public String removeOuterParentheses(String S) {
String res = "";
int cnt = 0;
int pos = 0;
String tmp = "";
for(int i = 0; i < S.length(); i ++){
tmp += (S.charAt(i) + "");
if(S.charAt(i) == '('){
cnt += 1;
}else {
cnt -= 1;
}
if(cnt == 0){
int len = tmp.length();
res += tmp.substring(1,len-1);
tmp = "";
}
}
return res;
}
注: 限作者水平有限,有任何问题欢迎评论区留言或者私信。欢迎幸福的骚扰