leecode.301. 删除无效的括号

题目

删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。

示例一

输入: “()())()”
输出: ["()()()", “(())()”]

思路分析

  • 我们使用一个队列来存储键值对<string,int>,前面表示当前的字符串,后面表示已删除的字符的个数。
  • 我们按照层次遍历的思想按照BFS来遍历这个队列。
  • 取出队首元素,判断当前字符串是否合法,如果合法且小于全局的最小值,更新答案;如果和全局数值相等,说明当前是重复;否则,不合法。
  • 如果当前字符串不合法,我们尝试进行删除该字符串中的字符。然后重复上述过程。

代码

class Solution {
public:
    bool  isVaild(string s){
        int count = 0;
        for(auto c : s){
            if(c == '(') count++;
            else if(c == ')') count--;
            if(count < 0) return false;
        }
        return count == 0;
    }

    vector<string> removeInvalidParentheses(string s) {
        unordered_set<string> ans;
        queue<pair<string, int>> q;
        unordered_map<string, bool> vis;
        q.push({s, 0});//s表示当前的字符串,0表示目前的删除的字符
        int minn = 0x3f3f3f3f;
        vis[s] = true;
        while(!q.empty()){
            int n = q.size();
            for(int i = 0;i < n;i++){
                auto cur = q.front();
                q.pop();
                string curS = cur.first;
                int tot = cur.second, m = curS.size();
                if(isVaild(curS) && tot <= minn){
                    if(tot < minn){
                        ans.clear();
                        minn = tot;
                    }
                    ans.insert(curS);
                    continue;
                }
                if(minn < 0x3f3f3f3f && ans.size() > 0) break;
                for(int j = 0;j < m;j++){//表示删除第j位的字符
                    if(curS[j] == '(' || curS[j] == ')'){
                        string temp =  curS.substr(0, j) + curS.substr(j + 1, m - j); 
                        if(!vis[temp] && tot + 1 < minn) {
                            q.push({temp, tot + 1});
                            vis[temp] = true;
                        }
                    } 
                }  
            }
        }
        vector<string> res(ans.begin(), ans.end());
        return res;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值