1. 程式人生 > >LeetCode題301—Remove Invalid Parentheses

LeetCode題301—Remove Invalid Parentheses

gen res bool all nim set集合 () div mov

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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]

思路:可以利用DFS或者BFS來解這道題,感覺還是BFS簡單點,即對於從給定的字符串通過移除 ( 或 ) 來構造所有可能的合法串,如果合法就加入到set集合中,不合法到到下一輪的BFS中。

public class Solution {
    public List<String> removeInvalidParentheses(String s) {
      List<String> res = new ArrayList<>();
      
      // sanity check
if (s == null) return res; Set<String> visited = new HashSet<>(); Queue<String> queue = new LinkedList<>(); // initialize queue.add(s); visited.add(s); boolean found = false; while (!queue.isEmpty()) { s
= queue.poll();
    // 如果當前層次中有合法解的話,只需要將當前層次中的字符串全部彈出判斷是否合法,停止BFS,這樣保證所得到的合法字符串是移除最少字符得到的
if (isValid(s)) { // found an answer, add to the result res.add(s); found = true; } if (found) continue; // generate all possible states for (int i = 0; i < s.length(); i++) { // we only try to remove left or right paren if (s.charAt(i) != ‘(‘ && s.charAt(i) != ‘)‘) continue; String t = s.substring(0, i) + s.substring(i + 1); if (!visited.contains(t)) { // for each state, if it‘s not visited, add it to the queue queue.add(t); visited.add(t); } } } return res; } // helper function checks if string s contains valid parantheses boolean isValid(String s) { int count = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == ‘(‘) count++; if (c == ‘)‘ && count-- == 0) return false; } return count == 0; } }

LeetCode題301—Remove Invalid Parentheses