• 301. 删除无效的括号 (JAVA)


    给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。

    返回所有可能的结果。答案可以按 任意顺序 返回。

    示例 1:

    输入: "()())()"
    输出: ["()()()", "(())()"]
    示例 2:

    输入: "(a)())()"
    输出: ["(a)()()", "(a())()"]
    示例 3:

    输入: ")("
    输出: [""]

    思路:这种一步一步生成答案合集的,一般使用递归。

    class Solution {
        public List<String> removeInvalidParentheses(String s) {
            int leftCount = 0;
            int rightCount = 0;
            int leftErr = 0;
            int rightErr = 0;
            result = new HashSet<>();
    
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == '(') {
                    leftCount++;
                } else if(s.charAt(i) == ')'){
                    if(leftCount > 0) {
                        leftCount--;
                    } else {
                        rightErr++;
                    }
                }
            }
            leftErr = leftCount;
    
            dfs(s, 0, leftErr, rightErr);
            return new ArrayList(result);
        }
    
        private void dfs(String s, int index, int leftErr, int rightErr){
            
            if(leftErr == 0 && rightErr == 0) {
                if(checkValid(s)) {
                    result.add(s);
                }
                return;
            } 
    
            if(index == s.length()) {
                return;
            }
    
            String tmpStr;
            if(s.charAt(index) == '(' && leftErr > 0) {
                tmpStr=s.substring(0, index)+s.substring(index+1);
                dfs(tmpStr, index, leftErr-1, rightErr);
            } else if(s.charAt(index) == ')' && rightErr > 0) {
                tmpStr=s.substring(0, index)+s.substring(index+1);
                dfs(tmpStr, index, leftErr, rightErr-1);
            } 
            dfs(s, index+1, leftErr, rightErr);
        }
    
        private boolean checkValid(String s) {
            int leftCount = 0;
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == '(') {
                    leftCount++;
                } else if(s.charAt(i)==')'){
                    if(leftCount > 0) {
                        leftCount--;
                    } else {
                        return false;
                    }
                }
            }
            if(leftCount != 0){
                return false;
            } else {
                return true;
            }
        }
        private Set<String> result;
    }
  • 相关阅读:
    一张900w的数据表,16s执行的SQL优化到300ms?
    webpack学习收集
    集合对象的string类型字段进行排序
    react 项目中使用antd的select组件placeholder不生效的解决方法
    React Hook做页面跳转以及携带参数,并且获取携带的值
    eclipse jar包 Source not found
    细说Redis分布式锁🔒
    Spring Boot中有多个@Async异步任务时,记得做好线程池的隔离!
    HDFS基本命令
    斐波那契数(Java)
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/14706918.html
Copyright © 2020-2023  润新知