0
点赞
收藏
分享

微信扫一扫

leetcode 301. Remove Invalid Parentheses

问题描述

给定一个由 '('、')' 和小写字母组成的字符串 S,你需要找出 S 中的所有有效的括号子串,并返回任意一个(或空字符串)。有效的括号子串是指符合有效括号表达式的子串,即任何时候左括号的数量都不会超过右括号的数量。

示例 1: 输入: "()" 输出: "()"

示例 2: 输入: ")(" 输出: ""

示例 3: 输入: "(a)()" 输出: "(a)()"

注意:

  1. S 的长度不超过 1000。
  2. S 只包含小写字母 '(' 和 ')'。
  3. 题目保证输入的字符串 S 是非空的。

解法一

解题思路:

我们需要找到所有有效的括号子串。一种方法是使用回溯法,尝试删除所有可能的无效括号,然后检查剩余的字符串是否有效。

/*
 * @lc app=leetcode.cn id=301 lang=javascript
 *
 * [301] Remove Invalid Parentheses
 */

// @lc code=start
function removeInvalidParentheses(S) {
    let res = new Set();
    const dfs = (s, left, right) => {
        if (left === 0 && right === 0) {
            if (isValid(s)) res.add(s);
            return;
        }
        if (left > 0 && s[0] === '(') {
            dfs(s.slice(1), left - 1, right);
        }
        if (right > 0 && s[0] === ')') {
            dfs(s.slice(1), left, right - 1);
        }
        if (s[0] !== '(' && s[0] !== ')') {
            dfs(s.slice(1), left, right);
        }
    };

    const isValid = (s) => {
        let balance = 0;
        for (const c of s) {
            if (c === '(') balance++;
            else if (c === ')') balance--;
            if (balance < 0) return false;
        }
        return balance === 0;
    };

    dfs(S, S.length - S.replace(/\(/g, '').length, S.length - S.replace(/\)/g, '').length);
    return res.size === 0 ? '' : Array.from(res)[0];
}
// @lc code=end
举报

相关推荐

0 条评论