zoukankan      html  css  js  c++  java
  • 【数据结构】算法 Minimum Remove to Make Valid Parentheses 移除无效的括号

    Minimum Remove to Make Valid Parentheses 移除无效的括号

    给出一个string,其中包含(, ),以及小写字母a~z组成,要求删掉最少的(),使得剩余的字符串是有效的括号字符串。

    Input: s = "a)b(c)d"
    Output: "ab(c)d"
    
    Input: s = "))(("
    Output: ""
    Explanation: An empty string is also valid.
    
    Input: s = "(a(b(c)d)"
    Output: "a(b(c)d)"
    

    思路

    要寻找到一个字符串中多余的括号,也就是说,无法成对匹配的都是多余的,那就通过boolarr 把有效的char标识出来,这样,再一次扫描的时候就把有效的char拼装成string

    public String minRemoveToMakeValid(String s) {
            int cnt =0; 
            boolean[] invalid = new boolean[s.length()];//true 无效,false 有效
            Stack<Integer> st = new Stack<>();
            for(int i=0;i<s.length();i++){
               char c = s.charAt(i);
               switch (c){
                    case '(':{  
                       cnt+=1;
                       st.push(i);
                       invalid[i] = true;
                   };
                   break;
                   case ')':{
                       cnt-=1;
                       if(!st.isEmpty()){
                        invalid[st.pop()]=false; 
                        invalid[i]=false;
                       }
                       else{
                           invalid[i] = true;
                       }
                   };break;
                   default:
                    invalid[i]=false;
                   break;
               }
                    
            }
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<s.length();i++ ){
                if(!invalid[i]){
                    sb.append(s.charAt(i));
                }
            }
            return sb.toString();
        }
    

    Tag

    stack

  • 相关阅读:
    SaveFileDialog控件
    OpenFileDialog组件打开文件....待续
    零碎笔记集合......
    Environment 类
    StatusStrip状态栏控件
    NotifyIcon制作任务栏托盘菜单
    ContextMenuStrip控件
    object sender ,EventArs e
    MenuItem
    TabControl控件
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14605407.html
Copyright © 2011-2022 走看看