努橙刷题编

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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"]

posted on 2017-11-08 17:19  努橙  阅读(216)  评论(0编辑  收藏  举报