LeetCode Remove Invalid Parentheses

原题链接在这里:https://leetcode.com/problems/remove-invalid-parentheses/

题目要求减少最小个数的非法括号,要求最小,就想到BFS.

Queue 里加入 原来的string s, 循环中从queue中poll出来一个string. 每次减掉一个括号,若是合法了就加到res中,同时停止继续enqueue, 只把queue中现有的一个level检查了就好。

若是没遇到合法的,就从头到尾减掉一个括号放回到queue中。

检查是否合法用isValid. 这种写法不需要stack, 节省了空间。

同时使用Set 来记录已经检查过的string, 检查过就不需要再次检查。

AC Java:

 1 public class Solution {
 2     public List<String> removeInvalidParentheses(String s) {
 3         List<String> res = new ArrayList<String>();
 4         LinkedList<String> queue = new LinkedList<String>();
 5         queue.offer(s);
 6         
 7         boolean found = false; //标签,检查是否找到了valid parentheses
 8         Set<String> hs = new HashSet<String>(); //存储已经检查过的string, 没有必要重复检查
 9         while(!queue.isEmpty()){
10             String str = queue.poll();
11             if(isValid(str)){
12                 res.add(str);
13                 found = true;
14             }
15             if(found){
16                 continue; //已经找到,就在本level中找剩下的就好了
17             }
18             for(int i = 0; i<str.length(); i++){ 
19                 if(str.charAt(i) != '(' && str.charAt(i) != ')'){
20                     continue;   //error, "x(" -> ["x",""]
21                 }
22                 String subStr = str.substring(0,i) + str.substring(i+1);
23                 if(!hs.contains(subStr)){
24                     hs.add(subStr);
25                     queue.offer(subStr);
26                 }
27             }
28         }
29         return res;
30     }
31     
32     private boolean isValid(String s){
33         int count = 0;
34         for(int i = 0; i<s.length(); i++){
35             if(s.charAt(i) == '('){
36                 count++;
37             }
38             if(s.charAt(i) == ')' && count-- == 0){
39                 return false;
40             }
41         }
42         return count == 0;
43     }
44 }

 

你可能感兴趣的:(LeetCode Remove Invalid Parentheses)