Fork me on GitHub

【数据结构】算法 Remove Outermost Parentheses 删除最外层的括号

Remove Outermost Parentheses 删除最外层的括号

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
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

posted @ 2021-04-15 09:31  WilliamCui  阅读(53)  评论(0)    收藏  举报