leetcode 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: [""]

 

 

删除多余的右括号,可看成以删除的括号为节点的dfs。记录最后删除的位置,避免重复如到位置3时删除位置2,位置4是删除位置1。

public List<String> removeInvalidParentheses(String s) {
        List<String> list=new ArrayList<>();
        dfs(s,list,0,')');
        return list;
    }
    public void dfs(String s,List list,int last,char c){//c='('or')'
        for(int i=0,count=0;i<s.length();i++){
            //找到多的c就递归
            if(s.charAt(i)=='('||s.charAt(i)==')'){
                count=s.charAt(i)==c?count-1:count+1;
            }
            if(count<0){//开始去掉之前的c
                for(int j=last;j<=i;j++){//删除之后的去重,一种情况重复4-1,3-2;4-2,3-1
                    //找到删掉的点开始深搜
                    if((j==0||s.charAt(j-1)!=c)&&s.charAt(j)==c){//等于c时去掉并递归
                        dfs(s.substring(0,j)+s.substring(j+1),list,j,c);
                    }
                }
                return;
            }
        }
        if(c==')'){
            dfs(reverse(s),list,0,'(');
            return;
        }
        list.add(reverse(s));
        
    }
    public String reverse(String s){
        StringBuilder sb=new StringBuilder();
        for(int i=s.length()-1;i>=0;i--){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }

参考:https://blog.csdn.net/qq508618087/article/details/50408894

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值