C++实现——Remove Invalid Parentheses

来源:互联网 发布:python unicode转ascii 编辑:程序博客网 时间:2024/06/06 12:38

这里写图片描述

【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
原创粉丝点击