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;
        }
  • 相关阅读:
    火狐flash插件
    centos 安装php ide (eclipse + php 插件)
    编译器的工作过程
    php中调用mysql的存储过程和存储函数
    mysql 高性能
    存储过程/游标/mysql 函数
    php 生成二维码
    frameset,frame应用,常用于后台
    html5 meta头部设置
    CAReplicatorLayer复制Layer和动画, 实现神奇的效果
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4940994.html
Copyright © 2011-2022 走看看