码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Invalid Parentheses 移除非法括号

时间:2015-11-07 13:35:07      阅读:484      评论:0      收藏:0      [点我收藏+]

标签:

 

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

Credits:
Special thanks to @hpplayer for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

 
这道题让我们移除最少的括号使得给定字符串为一个合法的含有括号的字符串,我们从小数学里就有括号,所以应该对合法的含有括号的字符串并不陌生,字符串中的左右括号数应该相同,而且每个右括号左边一定有其对应的左括号,而且题目中给的例子也说明了去除方法不唯一,我们需要找出所有合法的取法。参考了网上大神的解法,这道题首先可以用BFS来解,我们先把给定字符串排入队中,然后取出检测其是否合法,若合法直接返回,不合法的话,我们队其进行遍历,对于遇到的左右括号的字符,我们去掉括号字符生成一个新的字符串,如果这个字符串之前没有遇到过,将其排入队中,我们用哈希表记录一个字符串是否出现过。我们对队列中的每个元素都进行相同的操作,直到队列为空还没找到合法的字符串的话,那就返回空集,参见代码如下:
 
 
class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        vector<string> res;
        unordered_map<string, int> visited;
        queue<string> q;
        q.push(s);
        ++visited[s];
        bool found = false;
        while (!q.empty()) {
            s = q.front(); q.pop();
            if (isValid(s)) {
                res.push_back(s);
                found = true;
            }
            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 t) {
        int cnt = 0;
        for (int i = 0; i < t.size(); ++i) {
            if (t[i] == () ++cnt;
            if (t[i] == ) && cnt-- == 0) return false;
        }
        return cnt == 0;
    }
};

 

此题还有DFS的解法(未完待续。。。)

 

类似题目:

Different Ways to Add Parentheses

Longest Valid Parentheses

Generate Parentheses

Valid Parentheses

 

参考资料:

https://leetcode.com/discuss/67842/share-my-java-bfs-solution

https://leetcode.com/discuss/67825/backtracking-trick-here-eliminate-duplicates-without-map

https://leetcode.com/discuss/67821/dfs-and-bfs-java-solutions

 

LeetCode All in One 题目讲解汇总(持续更新中...)

 

[LeetCode] Remove Invalid Parentheses 移除非法括号

标签:

原文地址:http://www.cnblogs.com/grandyang/p/4944875.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!