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

301.Remove Invalid Parentheses

时间:2015-12-06 22:25:48      阅读:156      评论: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.

思路:BFS。首先将s压入队列,循环取出队列头部的字符串,如果其合法,将其加入返回的数组ret中,并设置bool常量found为true。因为我们返回的是括号数目最多的合法字符串,如果found为true,表明找到了一个合法的字符串,后面的字符串没有必要进行切割处理了,所以found为true,直接continue跳过循环。否则尝试切割字符串中的一个左右括号,将其压入队列q中,后续判断其是否合法。注意,为了保证字符串不出现重复,这里用了unordered_map判断是否出现重复字符串,只有首次出现的字符串才会进入队列q中。
  1. class Solution {
  2. private:
  3. bool isValid(string s){
  4. int count=0;
  5. for(int i=0;i<s.length();i++){
  6. if(s[i]==‘(‘)
  7. count++;
  8. else if(s[i]==‘)‘){
  9. if(count==0)
  10. return false;
  11. count--;
  12. }
  13. }
  14. return count==0;
  15. }
  16. vector<string> ret;
  17. public:
  18. vector<string> removeInvalidParentheses(string s) {
  19. unordered_map<string,int> map;
  20. queue<string> q;
  21. q.push(s);
  22. map[s]=1;
  23. bool found=false;
  24. while(!q.empty()){
  25. string str=q.front();
  26. q.pop();
  27. if(isValid(str)){
  28. ret.push_back(str);
  29. found=true;
  30. }
  31. if(found)
  32. continue;
  33. for(int i=0;i<str.length();i++){
  34. if(str[i]!=‘)‘&&str[i]!=‘(‘)
  35. continue;
  36. //将这个括号从字符串中去除
  37. string sub=str.substr(0,i)+str.substr(i+1);
  38. if(map.find(sub)==map.end()){
  39. q.push(sub);
  40. map[sub]=1;
  41. }
  42. }
  43. }
  44. return ret;
  45. }
  46. };

 




301.Remove Invalid Parentheses

标签:

原文地址:http://www.cnblogs.com/zhoudayang/p/5024435.html

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