【Leetcode】Remove Invalid Parentheses

来源:互联网 发布:淘宝客服要求 编辑:程序博客网 时间:2024/05/16 04:54

题目链接:https://leetcode.com/problems/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 ).

Examples:
“()())()” -> [“()()()”, “(())()”]
“(a)())()” -> [“(a)()()”, “(a())()”]
“)(” -> [“”]

思路:
暴力遍历 所有 删除该字符串一部分后的结果(一个个的删),若为为有效字符串则保留结果退出递归。 为了优化递归 对于没必要继续递归的分支进行剪枝。
那么哪些是没有必要递归的呢? 这就要计算当前字符串有多少个无效字符了,比如))(就是3,())就是1,用栈就能得到结果了。 当删除当前字符串某个字符后,若删除前字符的无效字符数 大于 删除后的无效字符数,则说明当前删除的字符是可以减少无效字符的,所以就往这个方向继续递归。 否则就没要继续递归了~~
又因为字符串是一个个逐个递归删除的,当遇到一个字符串的无效字符数为0的时候它当然就是最长的有效字符串~

算法:

    List<String> res = new ArrayList<String>();    public List<String> removeInvalidParentheses(String s) {        dsp(s);        return res;    }    Set<String> maps = new HashSet<String>();    public void dsp(String s){        int min = cals(s);        if(min==0){            res.add(s);            return;        }        for(int i=0;i<s.length();i++){            String next = s.substring(0,i)+s.substring(i+1,s.length());            if(!maps.contains(next)&&cals(next)<min){                maps.add(next);                dsp(next);            }        }    }    public int cals(String s){        Stack<Character> stack = new Stack<Character>();        for(int i=0;i<s.length();i++){            char c = s.charAt(i);            if(c!='('&&c!=')')                continue;            if(stack.isEmpty()){                stack.push(c);                continue;            }            if(c=='('){                stack.push(c);            }else if(c==')'){                if(stack.peek()=='('){                    stack.pop();                }else{                    stack.push(c);                }            }        }        return stack.size();    }
1 0