LeetCode Remove Invalid Parentheses

来源:互联网 发布:提高口才知乎 编辑:程序博客网 时间:2024/05/21 08:44

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;}} elsenum++;}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>


0 0