【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来求解这道题。
       每次将队列中第一个元素出队并判断其是否是有效的字符串,若是就加入结果向量result中,若不是则将该字符串删去一个括号的子串加入队列中。由于使用BFS算法,当找到一个有效的字符串后就不用继续寻找下去,因为之后添加的字符串删去的括号数一定大于最小的,不满足条件。
      
代码:

class Solution {
public:
    bool valid(string s)   //判断字符串是否有效
    {
        int count = 0;
        for(int i = 0;i<s.length();i++)
        {
            if(s[i] == '(')
            count++;
            else if(s[i] == ')')
            count--;
            if(count<0)
            return false;
        }
        if(count!=0)
        return false;
        return true;
    }
    vector<string> removeInvalidParentheses(string s) {
        vector<string> result;
        queue<string> q;
        set<string> visited;
        q.push(s);
        visited.insert(s);
        set<string>::iterator it;
        int tag = 0;
        while(!q.empty())
        {
            string temp = q.front();
            q.pop();
            if(valid(temp))
            {
                result.push_back(temp);
                tag = 1;
            }
            if(tag == 0)     //还没有找到有效的字符串
            {
                for(int i = 0;i<temp.length();i++)
                {
                    if(temp[i]!='('&&temp[i]!=')')
                    continue;
                    string tp = temp.substr(0,i)+temp.substr(i+1,temp.length());
                    it = visited.find(tp);
                    if(it == visited.end())      //没有遍历过 
                    {
                        q.push(tp);
                        visited.insert(tp);
                    }
                }
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值