301. Remove Invalid Parentheses

2022/4/7 6:20:47

本文主要是介绍301. Remove Invalid Parentheses,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Just use BFS to solve this problem:

1. put the s to queue

2. if s is not a valid string, then remove a '(' or ')', and then put to the queue.

3. once find valid strings, return.

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Set<String> res = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        queue.offer(s);
        Set<String> visited = new HashSet<>();
        visited.add(s);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                String str = queue.poll();
                if(isValid(str)){
                    res.add(str);
                }
                else{
                    for(int j=0;j<str.length();j++){
                        String temp = str.substring(0, j)+str.substring(j+1);
                        if(!visited.contains(temp)){
                            visited.add(temp);
                            queue.offer(temp);
                        }
                    }
                }
            }
            if(res.size()>0)
                return new ArrayList(res);
        }
        return new ArrayList(res);
    }
    
    private boolean isValid(String s){
        int count = 0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='(')
                count++;
            else if(s.charAt(i)==')'){
                if(count>0)
                    count--;
                else
                    return false;
            }
            
        }
        return count==0;
    }
}

 



这篇关于301. Remove Invalid Parentheses的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程