LeetCode Remove Invalid Parentheses

Description:

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

Solution:

先用一次Stack算出最少需要移去的括號數量

然後用DFS求出所有可能的String

注:這道題目還是那個問題,沒有給我們String的範圍,很難判斷用什麼方法……


<span style="font-size:18px;">import java.util.*;

public class Solution {
	HashSet<String> set = new HashSet<>();
	List<String> list;

	public List<String> removeInvalidParentheses(String s) {
		int n = s.length();
		int validNum = getValidNum(s);
		int removeNum = n - validNum;
		dfs(0, removeNum, s, "");
		list = new ArrayList<String>(set);
		return list;
	}

	public int getValidNum(String s) {
		int num = 0;
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if (ch == '(') {
				stack.add(ch);
			} else if (ch == ')') {
				if (!stack.isEmpty()) {
					stack.pop();
					num += 2;
				}
			} else
				num++;
		}
		return num;
	}

	public void dfs(int tot, int removeNum, String str, String neoStr) {
		if (removeNum == 0) {
			neoStr = neoStr + str.substring(tot, str.length());
			if (valid(neoStr))
				set.add(neoStr);
			return;
		}
		for (int i = tot; i < str.length() - removeNum + 1; i++) {
			char ch = str.charAt(i);
			if (ch != '(' && ch != ')')
				continue;
			dfs(i + 1, removeNum - 1, str, neoStr + str.substring(tot, i));
		}
	}

	boolean valid(String s) {
		Stack<Character> stack = new Stack<Character>();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if (ch == '(')
				stack.add(ch);
			else if (ch == ')') {
				if (stack.isEmpty())
					return false;
				stack.pop();
			}
		}
		return stack.isEmpty();
	}
}</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章