【Leetcode】Remove Invalid Parentheses

题目链接: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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值