LeetCode 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 ).
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
思路: bfs, 每层修改一个字符,只要出现一个合法的,就停止构造,把队列中的处理完就ok了。
AC代码:
class Solution { public: bool isvaild(string str) { int count = 0; for(int i=0; i<str.length(); i++) { if(str[i]!='(' && str[i]!=')') continue; if(str[i] == ')' && count == 0) return false; if(str[i] == '(') count+=1; else count -= 1; } return count == 0; } vector<string> removeInvalidParentheses(string s) { vector<string> ret; queue<string> q; set<string> st; q.push(s); st.insert(s); bool flag = false; while(!q.empty()) { string str = q.front(); q.pop(); if(isvaild(str)) { flag = true; ret.push_back(str); } if (flag) continue; for(int i=0; i<str.length(); i++) { if(str[i]!='(' && str[i]!=')') continue; string ss = str.substr(0,i) + str.substr(i+1); if(st.count(ss) > 0) continue; st.insert(ss); q.push(ss); } } return ret; } };

浙公网安备 33010602011771号