码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 301: Remove Invalid Parenthesis

时间:2017-09-04 09:50:31      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:att   list   har   UI   code   new   other   tostring   ==   

Note:

It could be other chars in the String. Do not count as invalid parenthesis.

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<>();
        remove(s, result, 0, 0, new char[]{‘(‘, ‘)‘});
        return result;
    }
    
    private void remove(String input, List<String> result, int lastI, int lastJ, char[] pattern) {
        for (int count = 0, i = lastI; i < input.length(); i++) {
            if (input.charAt(i) == pattern[0]) {
                count++;
            }
            if (input.charAt(i) == pattern[1]) {
                count--;
            }
            
            if (count >= 0) {
                continue;
            }
            
            for (int j = lastJ; j <= i; j++) {
                if (input.charAt(j) == pattern[1] && (j == lastJ || input.charAt(j - 1) != pattern[1])) {
                    remove(input.substring(0, j) + input.substring(j + 1), result, i, j, pattern);
                }
            }
            return;
        }
        
        String reversed = new StringBuilder(input).reverse().toString();
        if (pattern[0] == ‘(‘) {
            remove(reversed, result, 0, 0, new char[]{‘)‘, ‘(‘});
        } else {
            result.add(reversed);
        }
    }
}

 

LeetCode 301: Remove Invalid Parenthesis

标签:att   list   har   UI   code   new   other   tostring   ==   

原文地址:http://www.cnblogs.com/shuashuashua/p/7472058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!