zoukankan      html  css  js  c++  java
  • [leetcode] Remove Invalid Parentheses

    题目:

    Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
    
    Note: The input string may contain letters other than the parentheses ( and ).
    
    Examples:
    "()())()" -> ["()()()", "(())()"]
    "(a)())()" -> ["(a)()()", "(a())()"]
    ")(" -> [""]

    分析:题目的意思是最少去掉无效括号的个数,可能去掉1个括号,也可能去掉2个,3个等等。我们可以借助广度优先搜索(BFS)的思想,如下:

                                 "())()"
                                 
     去掉1个    "))()"     "()()"   "()()"    "()))"        "())("
                     
     去掉2个  ")()"      .................................
    
     ................

    Java代码如下:

        public List<String> removeInvalidParentheses(String s) {
            List<String> result = new ArrayList<String>();
            Set<String> hs = new HashSet<String>(); 
            Queue<String> queue = new LinkedList<String>();
            boolean find = false;
            queue.offer(s);
            hs.add(s);
            while (! queue.isEmpty()) {
                String str = queue.poll();
                if (isValid(str)) {
                    result.add(str);
                    find = true;
                }
                if (find) {
                    continue;
                }
                for (int i = 0; i < str.length(); i++) {
                    if (str.charAt(i) != '(' && str.charAt(i) != ')') {
                        continue;
                    }
                    String tmp = str.substring(0, i) + str.substring(i + 1);
                    if (! hs.contains(tmp)) { //记录已经添加到队列的元素,防止重复计算。
                        hs.add(tmp);
                        queue.offer(tmp);
                    }
                }
            }
            return result;
        }
        public boolean isValid(String str) {
            int count = 0;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '(') {
                    count++;
                } else if (str.charAt(i) == ')') {
                    if (count > 0) {
                        count--;
                    } else {
                        return false;
                    }
                }
            }
            return count == 0;
        }
  • 相关阅读:
    如何修改容器内的/etc/resolv.conf
    OpenShift DNS的机制
    OpenShift 容器日志和应用日志分离问题
    python办公自动化(一)PPTX
    python装饰器 语法糖
    一步一步FLASK(一)
    linux python 安装 pymssql
    定制flask-admin的主页
    复制pycharm虚拟环境
    离线安装pycharm数据库驱动
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4940994.html
Copyright © 2011-2022 走看看