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

Remove Invalid Parentheses

时间:2016-10-23 11:51:21      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:div   span   bst   nim   not   char   private   nbsp   letters   

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

 1 public class Solution {
 2     private List<String> res = new ArrayList<String>();
 3     private int max = 0;
 4     public List<String> removeInvalidParentheses(String s) {
 5         dfs(s, "", 0, 0);
 6         if (res.size() == 0) {
 7             res.add("");
 8         }
 9 
10         return res;
11     }
12 
13     private void dfs(String str, String subRes, int countLeft, int maxLeft) {
14         if (countLeft > str.length()) return;
15         if (maxLeft + str.length() / 2 < max) return;
16         if (str.length() == 0) {
17             if (countLeft == 0 && subRes.length() != 0) {
18                 if (maxLeft > max) {
19                     max = maxLeft;
20                 }
21                 if (max == maxLeft && !res.contains(subRes)) {
22                     res.add(subRes.toString());
23                 }
24             }
25             return;
26         }
27 
28         if (str.charAt(0) == () {
29             dfs(str.substring(1), subRes.concat("("), countLeft + 1, maxLeft + 1);
30             dfs(str.substring(1), subRes, countLeft, maxLeft);
31         } else if (str.charAt(0) == )) {
32             if (countLeft > 0) {
33                 dfs(str.substring(1), subRes.concat(")"), countLeft - 1, maxLeft);
34             }
35             dfs(str.substring(1), subRes, countLeft, maxLeft);
36         } else {
37             dfs(str.substring(1), subRes.concat(String.valueOf(str.charAt(0))), countLeft, maxLeft);
38         }
39     }
40 }

 

Remove Invalid Parentheses

标签:div   span   bst   nim   not   char   private   nbsp   letters   

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5989085.html

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