码迷,mamicode.com
首页 > 其他好文 > 详细

301. Remove Invalid Parentheses

时间:2016-07-04 06:36:22      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 301. Remove Invalid Parentheses
     * 2016-7-3 by Mingyang
     * 典型的BFS算法,就是利用queue每次把string放进去,然后删掉其中的一个
     * 再放入下一层,先把删掉一个所出现的所有情况判断完了再继续
     */
    public List<String> removeInvalidParentheses(String s) {
        List<String> res = new ArrayList<>();
        // sanity check
        if (s == null)
            return res;
        Set<String> visited = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        // initialize
        queue.add(s);
        visited.add(s);
        boolean found = false;
        while (!queue.isEmpty()) {
            s = queue.poll();
            if (isValid(s)) {
                // found an answer, add to the result
                res.add(s);
                found = true;
            }
    //在又找到的以后这个found可以阻止进一步往下继续走,保证了最小步数
            if (found)
                continue;
            // generate all possible states
            for (int i = 0; i < s.length(); i++) {
                // we only try to remove left or right paren
                if (s.charAt(i) != ‘(‘ && s.charAt(i) != ‘)‘)
                    continue;
                String t = s.substring(0, i) + s.substring(i + 1);
           if (!visited.contains(t)) {
            // for each state, if it‘s not visited, add it to the queue
              queue.add(t);
              visited.add(t);
                }
            }
        }
        return res;
    }
    // helper function checks if string s contains valid parantheses
    boolean isValid(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ‘(‘)
                count++;
            if (c == ‘)‘ && count-- == 0)
                return false;
        }
        return count == 0;
    }

 

301. Remove Invalid Parentheses

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5639332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!