[LeetCode] Remove Invalid Parentheses

This problem can be solved very elegantly using BFS, as in this post.

The code is rewritten below in C++.

 1 class Solution {
 2 public:
 3     vector<string> removeInvalidParentheses(string s) {
 4         vector<string> parens;
 5         queue<string> candidates;
 6         unordered_set<string> visited;
 7         candidates.push(s);
 8         visited.insert(s);
 9         bool found = false;
10         while (!candidates.empty()) {
11             string now = candidates.front();
12             candidates.pop();
13             if (isValid(now)) {
14                 parens.push_back(now);
15                 found = true;
16             }
17             if (!found) {
18                 int n = now.length();
19                 for (int i = 0; i < n; i++) {
20                     if (now[i] == '(' || now[i] == ')') {
21                         string next = now.substr(0, i) + now.substr(i + 1);
22                         if (visited.find(next) == visited.end()) {
23                             candidates.push(next);
24                             visited.insert(next);
25                         }
26                     }
27                 }
28             }
29         }
30         return parens;
31     }
32 private:
33     bool isValid(string& s) {
34         int c = 0, n = s.length();
35         for (int i = 0; i < n; i++) {
36             if (s[i] == '(') c++;
37             if (s[i] == ')' && !c--) return false;
38         }
39         return !c;
40     }
41 };

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值