C++实现——Remove Invalid Parentheses

这里写图片描述

【Leetcode_301】
//去掉最少的括号,使得字符串合理匹配
/*
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来解,我们先把给定字符串排入队中,
  然后取出检测其是否合法,若合法直接返回,不合法的话,我们对其进行遍历,
  对于遇到的左右括号的字符,我们去掉括号字符生成一个新的字符串,如果这个
  字符串之前没有遇到过,将其排入队中,我们用哈希表记录一个字符串是否出现
  过。我们对队列中的每个元素都进行相同的操作,直到队列为空还没找到合法的
  字符串的话,那就返回空集,
*/
#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;
vector<string> removeInvalidParentheses(string s) {

    vector<string> res;
    queue<string> q;
    map<string, int> visited;
    q.push(s);
    ++visited[s];

    while (!q.empty()) {
        bool found = false;
        s = q.front();
        q.pop();
        //判断是否合理
        if (isvalid(s)) {
            found = true;
            res.push_back(s);
        }
        if (found)continue;
        //如果此字符串不合理则
        for (int i = 0;i < s.size();i++) {
            if (s[i] != ')'&&s[i] != '(')continue;
            //拼凑新的字符串
            string t = s.substr(0, i) + s.substr(i + 1);
            //如果新的字符串之前没遇到过就将其入队列
            if (visited.find(t) == visited.end()) {
                q.push(t);
                ++visited[t];
            }
        }

    }

    return res;
}
//验证是否是合理串的函数(之前用栈实现过这个功能)
bool isvalid(string s) {

    int cnt = 0;
    for (int i = 0;i < s.size();i++) {

        if (s[i] == '(')++cnt;
        if (s[i] == ')'&&cnt-- == 0)return false;
    }
    return cnt == 0;
}

//测试函数
int main() {

    string s;
    while (cin >> s) {

        vector<string> res = removeInvalidParentheses(s);

        for (auto a : res) {
            cout << a << endl;
        }
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值