removeInvalidParentheses

来源:互联网 发布:淘宝打假赚钱 编辑:程序博客网 时间:2024/06/16 12:54

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

先占个坑,实现了一个naive版本的。dfs的时候把不符合条件的结果也保存进去了,需要过滤一下,而且是用的set去重。看网上对于统计有一种方法跟我之前想的很类似。对于
")()(" 这种情况网上给出了先预处理左边跟右边的这种情况,我觉得是合理的其他的应该可以通过维护两个left, right变量,表示左边右边一共可以使用的括号数来进行拼接。以后补上。

代码:

public List<String> removeInvalidParentheses(String s) {        if(s == null) return new ArrayList<>();        if(s.length() == 0){            List<String> ret = new ArrayList<>();            ret.add("");            return ret;        }        HashSet<String> result = new HashSet<>();        dfs(result, s, "", 0, 0, 0);        //需要找到最长的那种情况,过滤一下        // List<String> answer = new ArrayList<>(result).stream().filter(str -> str.length() == maxLength).collect(Collectors.toList());        List<String> answer = new ArrayList<>();        for(String item: result){            if(item.length() == maxLength){                answer.add(item);            }        }        if(answer.size() == 0){            answer.add("");        }        return answer;    }    private int maxLength = Integer.MIN_VALUE;    private void dfs(HashSet<String> result, String s, String cur, int left, int right, int index){        if(index == s.length()){            if(left == right && cur.length() != 0){                result.add(cur);                maxLength = Math.max(maxLength, cur.length());            }            return;        }        char ch = s.charAt(index);        if(!isParen(ch)){            dfs(result, s, cur+ch, left, right, index+1);        }else{            if(ch == '('){                    dfs(result, s, cur+"(", left+1, right, index+1);            }            if(ch == ')'){                if( right < left){                    dfs(result, s, cur+")", left, right+1, index+1);                }            }            dfs(result, s, cur, left, right, index+1);        }    }    private boolean isParen(char ch){        return ch == '(' || ch == ')';    }


0 0
原创粉丝点击