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

[LeetCode] 301. Remove Invalid Parentheses

时间:2017-11-08 20:06:49      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:special   ati   ++   tput   queue   cas   ref   length   not   

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())()"]
")(" -> [""]

Credits:
Special thanks to @hpplayer for adding this problem and creating all test cases.

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Queue<String> queue = new LinkedList<>();
        List<String> result = new ArrayList<>();
        Set<String> visited = new HashSet<>();
        visited.add(s);
        queue.offer(s);
        while(!queue.isEmpty()) {
            String tmp = queue.poll();
            if (isValid(tmp)) {
                result.add(tmp);
                continue;
            }
            if (result.size() != 0 && tmp.length() <= result.get(0).length()) {
                continue;
            }
            for (int i = 0; i < tmp.length(); i++) {
                if (tmp.charAt(i) != ‘(‘ && tmp.charAt(i) != ‘)‘) {
                    continue;
                }
                String newTmp = tmp.substring(0, i) + tmp.substring(i + 1, tmp.length());
                if (visited.contains(newTmp)) {
                    continue;
                }
                visited.add(newTmp);
                queue.offer(newTmp);
            }
        }
        return result;
    }
    
    private boolean isValid(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ‘(‘) {
                count++;
            }
            if (s.charAt(i) == ‘)‘) {
                if (count <= 0) {
                    return false;
                }
                count--;
            }
        }
        return count == 0;
    }
}

 

Failed case: remove the minimum number
Input:
"()())()"
Output:
["(())()","()()()","()()","(())","()",""]
Expected:
["(())()","()()()"]

Failed case: remove parentheses only
Input:
"x("
Output:
["x",""]
Expected:
["x"]

[LeetCode] 301. Remove Invalid Parentheses

标签:special   ati   ++   tput   queue   cas   ref   length   not   

原文地址:http://www.cnblogs.com/chencode/p/remove-invalid-parentheses.html

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