301. 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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]
class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> res = new ArrayList();
        if(s == null) return res;
        boolean inthislevel = false;
        Set<String> set = new HashSet<>();
        Queue<String> q = new LinkedList();
        q.add(s);
        set.add(s);

        while(!q.isEmpty()) {
            String cur = q.poll();
            if(isValid(cur)) {
                inthislevel = true;
                res.add(cur);
            }
            if(inthislevel) continue;
            
            for(int i = 0; i < cur.length(); i++) {
                if(cur.charAt(i) != '(' && cur.charAt(i) != ')') continue;
                String t = cur.substring(0, i) + cur.substring(i+1, cur.length());
                if(!set.contains(t)) {
                    set.add(t);
                    q.add(t);
                }
            }
        }
        return res;
    }
    public boolean isValid(String s) {
        int count = 0;
        for(char c: s.toCharArray()) {
            if(c == '(') count++;
            else if(c == ')'){
                count--;
                if(count < 0) return false;
            }
        }
        return count == 0;
    }
}

这题的逻辑还挺简单的(看了答案后 https://leetcode.com/problems/remove-invalid-parentheses/discuss/75032/Share-my-Java-BFS-solution

总结:

This question asked us to return the valid string that made by remove minimum parenthesis.

So we can think like this, we start from removing one parenthesis and check if there's valid answer, if all remove-one string are not valid, we go to the next stage which is remove two ... and so On

One thing need to pay attention is once we found a valid string in current level, we just use a boolean flag and make it true, then we just need to go through strings in current level instead going deeper.

Then to realize this, we use a queue to store current level's strings, a HashSet to store visited mid-point strings to avoid repeat answers.

Then a boolean variable inthislevel which means we found valid answer in this level and don't need to go deeper

In every level we tried to remove one parenthesis and add it to set and queue.

Another thing is when we encounter non parenthesis chars ,we just skip.

上一篇:如何在@括号(“Luke”)之类的Java注释中使用括号内没有属性?


下一篇:Leetcode 20题 有效的括号(Valid Parentheses) Java语言求解