Leetcode 301. Remove Invalid Parentheses FB-TAG

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

   思路:有一个要点是,要从左往右,也要从右往左。题意就是在表达式里删除最少的活好使之有效。

   用count来计算左右括号是否平衡,左加右减。如果平衡了且当前的last_i等于char[]里的右边,就进入循环去判断,然后开始每次去掉第一个遇到的par[1]. last_j 记录最后一个删除的元素。

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> ans = new ArrayList<String>();
        remove(s, ans, 0, 0, 0, new char[] {'(', ')'});
        return ans;
    }
   private void remove(String s, List<String> ans, int count, int last_i, int last_j, char[] par) {
       if (last_i == s.length() && par[0] == ')') {
            System.out.println("1+"+s);
            ans.add(new StringBuilder(s).reverse().toString());
             return;
         }
       if (last_i == s.length() && par[0] == '(') {
           System.out.println("2:"+s);
           String reverse = new StringBuilder(s).reverse().toString();
           System.out.println("1:"+reverse);
             remove(reverse, ans, 0, 0, 0, new char[] {')', '('});
             return;
        }
       char c = s.charAt(last_i);
       if(c==par[1] && count ==0){
           for(int j= last_j;j<=last_i;j++){
               if(s.charAt(j) == par[1] &&(j == last_j ||s.charAt(j-1)!=par[1])){
                   remove(s.substring(0,j) + s.substring(j+1), ans,0,last_i, j, par);
               }
           }
        }else{
           if(c == par[0])count++;
            if(c == par[1])count--;
           remove(s, ans, count, last_i + 1, last_j, par);
       }
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值