Remove Outermost Parentheses 删除最外层的括号
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Example 4:
Input: s = "([)]"
Output: false
Example 5:
Input: s = "{[]}"
Output: true
思路
从开始扫描,cnt计数,遇到'(',cnt加1;遇到')',cnt减1。cnt==0时,一个序列扫描完毕,从序列的第二位截取到倒数第二位。
public String removeOuterParentheses(String S) {
StringBuilder ret =new StringBuilder();
for (int i = 0 ,pre =0,cnt =0; i < S.length() ; i++) {
//pre 是序列开始
if(S.charAt(i)=='('){
cnt+=1;
}
else{
cnt-=1;
}
if(cnt!=0){
continue;
}
int begin = pre+1;
int end = i;
ret.append(S.substring(begin,end)) ;//从begin开始,截到end-1
pre = i+1;
}
return ret.toString();
}
Tag
stack