LeetCode 301. Remove Invalid Parentheses(删除无效的括号)

50 篇文章 0 订阅
37 篇文章 0 订阅

原题网址: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())()"]
")(" -> [""]

方法一:广度优先搜索。

public class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Set<String> visit = new HashSet<>();
        List<String> results = new ArrayList<>();
        LinkedList<String> queue = new LinkedList<>();
        queue.add(s);
        boolean succ = false;
        while (!queue.isEmpty()) {
            String q = queue.remove();
            if (succ) match(q, results); else succ = match(q, visit, queue, results);
        }
        return results;
    }
    
    private void match(String s, List<String> results) {
        // System.out.printf("Try matching %s\n", s);
        int match = 0;
        for(int i=0; i<s.length(); i++) {
            if (s.charAt(i) == '(') match ++;
            else if (s.charAt(i) == ')') match --;
            if (match < 0) return;
        }
        if (match == 0) results.add(s);
        // System.out.printf("Try matching %s successfully\n", s);
    }
    
    private boolean match(String s, Set<String> visit, LinkedList<String> queue, List<String> results) {
        // System.out.printf("Try matching %s\n", s);
        int match = 0;
        for(int i = 0; i < s.length(); i ++) {
            if (s.charAt(i) == '(') match ++;
            else if (s.charAt(i) == ')') match --;
            if (match < 0) {
                for(int j=0; j<=i; j++) {
                    if (s.charAt(j) != ')') continue;
                    String r = s.substring(0, j) + s.substring(j+1);
                    if (visit.contains(r)) continue;
                    visit.add(r);
                    queue.add(r);
                }
                // System.out.printf("Try matching %s fail, queue=%s\n", s, queue);
                return false;
            }
        }
        if (match == 0) {
            results.add(s);
            // System.out.printf("Try matching %s successfully\n", s);
            return true;
        }
        match = 0;
        for(int i = s.length()-1; i >= 0; i --) {
            if (s.charAt(i) == ')') match ++;
            else if (s.charAt(i) == '(') match --;
            if (match < 0) {
                for(int j=s.length()-1; j>=i; j--) {
                    if (s.charAt(j) != '(') continue;
                    String r = s.substring(0, j) + s.substring(j+1);
                    if (visit.contains(r)) continue;
                    visit.add(r);
                    queue.add(r);
                }
                // System.out.printf("Try matching %s fail, queue=%s\n", s, queue);
                return false;
            }
        }
        // System.out.printf("Try matching %s fail, queue=%s\n", s, queue);
        return false;
    }
}


方法二:深度优先搜索。

public class Solution {
    private Set<String> visit = new HashSet<>();
    private List<String> results = new ArrayList<>();
    
    private void removeLeft(String s) {
        int match = 0;
        for(int i=s.length()-1; i>=0; i--) {
            if (s.charAt(i) == ')') match ++;
            else if (s.charAt(i) == '(') match --;
            if (match < 0) {
                for(int j=s.length()-1; j>=i; j--) {
                    if (s.charAt(j) != '(') continue;
                    String r = s.substring(0, j) + s.substring(j+1);
                    if (visit.contains(r)) continue;
                    visit.add(r);
                    removeLeft(r);
                }
                return;
            }
        }
        results.add(s);
    }
    private void removeRight(String s) {
        int match = 0;
        for(int i=0; i<s.length(); i++) {
            if (s.charAt(i) == '(') match ++;
            else if (s.charAt(i) == ')') match --;
            if (match < 0) {
                for(int j=0; j<=i; j++) {
                    if (s.charAt(j) != ')') continue;
                    String r = s.substring(0, j) + s.substring(j+1);
                    if (visit.contains(r)) continue;
                    visit.add(r);
                    removeRight(r);
                }
                return;
            }
        }
        if (match == 0) {
            results.add(s);
            return;
        }
        removeLeft(s);
    }
    public List<String> removeInvalidParentheses(String s) {
        removeRight(s);
        return results;
    }
}

方法三:先删除无效的右括号,再删除无效的左括号,深度优先搜索。

这道题我没有做出好的解法,参考:http://algobox.org/remove-invalid-parentheses/

精妙之处在于:使用lastj保存上一次发现不匹配的位置和上一次删除括号的位置。

但如何证明唯一性?这个我还没有搞懂。

public class Solution {
    private void removeLeft(String s, int lastI, int lastJ, List<String> rs) {
        int match = 0;
        for(int i=lastI; i<s.length() && i>=0; i--) {
            if (s.charAt(i) == ')') match ++;
            else if (s.charAt(i) == '(') match --;
            if (match >= 0) continue;
            for(int j=lastJ; j<s.length() && j>=i; j--) {
                if (s.charAt(j) != '(') continue;
                if (j==lastJ || s.charAt(j+1) != '(') removeLeft(s.substring(0, j) + s.substring(j+1, s.length()), i-1, j-1, rs);
            }
            return;
        }
        rs.add(s);
    }
    private void removeRight(String s, int lastI, int lastJ, List<String> rs) {
        int match = 0;
        for(int i=lastI; i<s.length(); i++) {
            if (s.charAt(i) == '(') match ++;
            else if (s.charAt(i) == ')') match --;
            if (match >= 0) continue;
            for(int j=lastJ; j<=i; j++) {
                if (s.charAt(j) != ')') continue;
                if (j==lastJ || s.charAt(j-1) != ')') removeRight(s.substring(0, j) + s.substring(j+1, s.length()), i, j, rs);
            }
            return;
        }
        removeLeft(s, s.length()-1, s.length()-1, rs);
    }
    public List<String> removeInvalidParentheses(String s) {
        List<String> results = new ArrayList<>();
        removeRight(s, 0, 0, results);
        return results;
    }
}

带注释:

public class Solution {
    private void removeLeft(String s, int matchTo, int removeTo, List<String> results) {
        int matched = 0;
        for(int m=matchTo; m>=0; m--) {
            if (s.charAt(m) == ')') matched ++;
            else if (s.charAt(m) == '(') matched --;
            if (matched >= 0) continue;
            for(int r=removeTo; r>=m; r--) {
                //检查是左括号才能删除
                if (s.charAt(r) != '(') continue;
                if (r==removeTo || s.charAt(r+1) != '(') removeLeft(s.substring(0, r)+s.substring(r+1), m-1, r-1, results);
            }
            //如果本次有删除,则留待后面加入到results
            return;
        }
        results.add(s);
    }
    private void removeRight(String s, int matchTo, int removeTo, List<String> results) {
        int matched = 0;
        for(int m=matchTo; m<s.length(); m++) {
            if (s.charAt(m) == '(') matched ++;
            else if (s.charAt(m) == ')') matched --;
            if (matched >= 0) continue;
            for(int r=removeTo; r<=m; r++) {
                //检查是右括号才能删除
                if (s.charAt(r) != ')') continue;
                if (r==removeTo || s.charAt(r-1) != ')') removeRight(s.substring(0, r)+s.substring(r+1), m, r, results);
            }
            //如果本次有删除,则留待后面加入到results
            return;
        }
        removeLeft(s, s.length()-1, s.length()-1, results);
    }
    public List<String> removeInvalidParentheses(String s) {
        List<String> results = new ArrayList<>();
        removeRight(s, 0, 0, results);
        return results;
    }
}


  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值