301. Remove Invalid Parentheses

来源:互联网 发布:阿里云香港服务器能放 编辑:程序博客网 时间:2024/05/29 10:53

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

public class Solution {    public static boolean validP(String s){if(s == null || s.length() == 0){return true;}if(s.startsWith(")")){return false;}int count = 0;for(int i=0; i<s.length(); i++){if(s.charAt(i) == '('){count++;}if(s.charAt(i) == ')'){if(count == 0){return false;}count--;}}return count == 0;}public List<String> removeInvalidParentheses(String s) {List<String> result = new ArrayList<String>();Queue<String> queue = new LinkedList<String>();HashSet<String> map = new HashSet<String>();queue.offer(s);map.add(s);boolean found = false;while(!queue.isEmpty()){    int left = 0;    int right = 0;s = queue.peek();queue.poll();if(validP(s)){result.add(s);found = true;}if(found){continue;}for(int i=0; i<s.length(); i++){    if(s.charAt(i) == '('){        left++;    }    if(s.charAt(i) == ')'){        right++;    }}for(int i=0; i<s.length(); i++){    char current =s.charAt(i);if((current =='(' && left >= right) || (current==')' && right > left)){String n = s.substring(0, i) + s.substring(i + 1, s.length());if(!map.contains(n)){//剪枝:算好左右括号的数量,不用减少的那一个。queue.offer(n);map.add(n);}}}}return result;    }}


0 0
原创粉丝点击