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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值