[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;
    }

 

posted @ 2015-11-05 22:03  lasclocker  阅读(331)  评论(0编辑  收藏  举报