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 ).

思路:

BFS

首先定义一个函数valid,检验字符串中'('数量是否等于')'数量,当然,在从前往后遍历时,只要')'比'('数量多,就表明肯定失败,就不需要往后遍历了。

将字符串s压入队列中,如果队列不为空,取最前面元素出队,如果此字符串valid,将其压入result列表中,并将found置为true,否则,如果found不为true,那么删掉一个'('或')'作为字串,至于删除的位置,从头到尾哪个地方都可以,将新形成的字串们都压入队列中(前提是之前这个样子的字串没有出现过,因此要定义一个unordered_map来记录已经访问过的字符串)。当然found还有一个非常重要的作用,因为题目是要求最长串,因此一旦found为true了,那之后队列中出来的元素就不需要删除'('或')'形成子串了。

代码:

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        vector<string> result;
        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 (valid(str)){
                result.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 result;
    }
    bool valid(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;
    }
};

DFS:

首先关注')',如果')'多出来了,那就需要删除一个,此处删除哪个都可以,那就删除最靠前的那个,然后用这个字串继续DFS,直到不需要删了,然后将得到的字符串倒过来,用相同的方法看有没有多余的'(',如果有就按之前的方法继续删,最终就能得到答案。

代码:

class Solution {
public:
    void DFS(string s, char ch, int last)
    {
        for(int i = 0, cnt = 0; i < s.size(); i++)
        {
            if(s[i]=='('||s[i]==')') s[i]==ch?cnt++:cnt--;
            if(cnt <= 0) continue;
            for(int j = last; j <= i; j++)
            {
                if(s[j] == ch && (j ==last || s[j-1]!= ch))
                    DFS(s.substr(0, j)+s.substr(j+1), ch, j);
            }
            return;
        }
        reverse(s.begin(), s.end());
        if(ch == ')') return DFS(s, '(', 0);
        ans.push_back(s);
    }
    
    vector<string> removeInvalidParentheses(string s) {
        DFS(s, ')', 0);
        return ans;
    }
private:
    vector<string> ans;
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值