301. Remove Invalid Parentheses(bfs,hard)

本文介绍了一种使用队列和集合来解决移除最少数量的无效括号问题的方法,以使输入字符串有效。通过示例展示了如何寻找所有可能的结果。

dfs 不易处理,易超时
主要是借助队列和set来做(相当于一层一层的来找,找到就可以退出,因为要求出最小删除)


题目地址

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())()"]
")(" -> [""]

ac

class Solution {
public:

    //判断是否是合法的字符串
    bool isValid(string s)
    {
        int count = 0;
        for (int i = 0; i<s.length(); i++)
        {
            if (s[i] == '(')
                count++;
            else if (s[i] == ')'){
                if (count == 0)
                    return false;
                count--;
            }
        }
        return count == 0;
    }

    vector<string> ret;

    vector<string> removeInvalidParentheses(string s)
    {
        unordered_map<string, int> map;
        queue<string> q;
        q.push(s);
        map[s] = 1;
        bool found = false;
        while (!q.empty())
        {
            string str = q.front();
            q.pop();
            if (isValid(str)){
                ret.push_back(str);
                found = true;
            }
            if (found)
                continue;
            for (int i = 0; i<str.length(); i++)
            {
                if (str[i] != ')'&&str[i] != '(')
                    continue;
                //将这个括号从字符串中去除, 即这个括号要或者不要
                string sub = str.substr(0, i) + str.substr(i + 1);
                if (map.find(sub) == map.end()) //避免重复
                {
                    q.push(sub);
                    map[sub] = 1;
                }
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值