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

思路:BFS。首先将s压入队列,循环取出队列头部的字符串,如果其合法,将其加入返回的数组ret中,并设置bool常量found为true。因为我们返回的是括号数目最多的合法字符串,如果found为true,表明找到了一个合法的字符串,后面的字符串没有必要进行切割处理了,所以found为true,直接continue跳过循环。否则尝试切割字符串中的一个左右括号,将其压入队列q中,后续判断其是否合法。注意,为了保证字符串不出现重复,这里用了unordered_map判断是否出现重复字符串,只有首次出现的字符串才会进入队列q中。

class Solution {
public:
    private:
    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;
public:
    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;
    }

};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值