zoukankan      html  css  js  c++  java
  • 【数据结构】算法 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

  • 相关阅读:
    Oracle和MySQL的对比
    mysql的默认隔离级别
    mysql数据库中锁机制的详细介绍
    什么电影是好电影
    周记 2019.4.8~4.14
    周记 2019.3.25~2019.3.31
    IntelliJ Idea 使用笔记
    笔记
    kafka总结
    Spring boot
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14605400.html
Copyright © 2011-2022 走看看