LeetCode题解——Remove Invalid Parentheses
2015-12-14 22:29
399 查看
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
Examples:
解题思路:
1. 如果给我们一个字符串,首先去掉不合法的首字符即')'以及不合法的尾字符‘(’, 将其变为以‘(’开头,以‘)’结尾的字符串: (.......)
2. 对这个字符串,我们需要统计它有多少个不合法的‘(’,以及‘)’,分别用num1和num2表示。
3. batracking, 我们每次判断去掉一个字符后的字符串是否是合法字符串,是的话那么将该字符串存入结果字符,并递归回溯。 否则,继续处理。
Note: The input string may contain letters other than the parentheses
(and
).
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
解题思路:
1. 如果给我们一个字符串,首先去掉不合法的首字符即')'以及不合法的尾字符‘(’, 将其变为以‘(’开头,以‘)’结尾的字符串: (.......)
2. 对这个字符串,我们需要统计它有多少个不合法的‘(’,以及‘)’,分别用num1和num2表示。
3. batracking, 我们每次判断去掉一个字符后的字符串是否是合法字符串,是的话那么将该字符串存入结果字符,并递归回溯。 否则,继续处理。
class Solution { public: vector<string> removeInvalidParentheses(string& s) { vector<string> ret; int num1 = 0, num2 = 0, sum = 0; int beg = 0, end = s.size()-1; while(s[beg]==')') beg++; while(s[end]=='(') end--; s = s.substr(beg,end-beg+1); for(int i=0 ;i<s.size();i++){ if(s[i]=='(') sum++; else if(s[i]==')') sum--; num2 = min(num2,sum); } num1 = sum - num2; removeInvalidParentheses(s,0,num1,num2,ret); return ret; } bool isValid(string s) { int sum = 0; for(auto &c : s) //check whether s is valid or not { if(c == '(') ++sum; else if(c == ')') --sum; if(sum < 0) return false; } return sum == 0; } void removeInvalidParentheses(string s,int beg, int num1, int num2, vector<string>& ret){ if(num1==0 && num2 == 0) { if(isValid(s)) ret.push_back(s); return; } for(int i = beg; i < s.size(); ++i) { string tmp = s; /* The num2 == 0 expression is hard to come up with. All invalid '(' can only appear after invalid ')', otherwise there is no invalid ')'. It's OK we don't add this num2 == 0 test, without which only slows down the performance a little bit, from 4ms to 12ms. */ if(num2 == 0 && num1 > 0 && tmp[i] == '(') { if(i == beg || tmp[i] != tmp[i - 1]) //Watch here! This is the trick to avoid duplicates. { tmp.erase(i, 1); removeInvalidParentheses(tmp, i, num1 - 1, num2, ret); } } if(num2 < 0 && tmp[i] == ')') { if(i == beg || tmp[i] != tmp[i - 1]) { tmp.erase(i, 1); removeInvalidParentheses(tmp, i, num1, num2 + 1, ret); } } } } };
相关文章推荐
- [MySQL] 实例讲解MYSQL数据库的查询优化技术
- URL之开源项目的在线网址
- 工具之OpenGrok的搭建方法
- Struts框架搭建的几个注意事项
- 修改文本框
- BZOJ 1034 泡泡堂
- JAVA代码实现执行CMD命令
- 普通用户之间无法通过ssh协议进行切换(su),即使输入正确的密码
- ARM_s5pv210_porting_2
- mysql 批量insert
- 4-5 求自定类型元素的最大值
- 构造HTTP请求Header实现“伪造来源IP”(转)
- 传递值对象
- Delphi使用TryStrToDate判断字符串是否为日期格式
- CentOS初始化Mysql5.7密码
- Struts2中的值栈和OGNL
- iOS开发之4种存储方式
- Android:通知随记1
- 白手起家学习数据科学 ——k-Nearest Neighbors之“例子篇”(九)
- iOS开发之CDiscreetNotificationView