【LeetCode】301. Remove Invalid Parentheses 删除无效的括号(Hard)(JAVA)
题目地址: https://leetcode.com/problems/remove-invalid-parentheses/
题目描述:
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: [""]
题目大意
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
解题方法
- 要判断一个字符串是否有无效的括号,可以先从左到右遍历左括号数始终大于等于右括号数,从右到左遍历右括号数始终大于等于左括号数
- 如果左到右遍历,中途遇到左括号数始终小于右括号数,说明这之前肯定需要删除一个左括号,那就删除这之前的一个左括号,然后把结果继续递归找出结果
- 从右往左遍历也是同样处理
- note: 如果遇到字符串有效,直接就返回当前字符串
class Solution {
public List<String> removeInvalidParentheses(String s) {
Set<String> set = new HashSet<>();
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
count++;
} else if (s.charAt(i) == ')') {
count--;
}
if (count >= 0) continue;
for (int j = 0; j <= i; j++) {
if (s.charAt(j) != ')') continue;
if (j != 0 && s.charAt(j - 1) == ')') continue;
List<String> next = removeInvalidParentheses(s.substring(0, j) + s.substring(j + 1));
set.addAll(next);
}
return new ArrayList<>(set);
}
if (count == 0) {
set.add(s);
return new ArrayList<>(set);
}
count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ')') {
count++;
} else if (s.charAt(i) == '(') {
count--;
}
if (count >= 0) continue;
for (int j = s.length() - 1; j >= i; j--) {
if (s.charAt(j) != '(') continue;
if (j != s.length() - 1 && s.charAt(j + 1) == '(') continue;
List<String> next = removeInvalidParentheses(s.substring(0, j) + s.substring(j + 1));
set.addAll(next);
}
break;
}
return new ArrayList<>(set);
}
}
执行耗时:8 ms,击败了58.29% 的Java用户
内存消耗:39.4 MB,击败了29.81% 的Java用户