给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。
返回所有可能的结果。答案可以按 任意顺序 返回。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-invalid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Solution {
private List<String> ans = new ArrayList<>();
private void solve(String s, int index, int lRemove, int rRemove, int left) {
if (lRemove == 0 && rRemove == 0 && isValid(s)) {
ans.add(s);
return;
}
for (int i = index; i < s.length(); ++i) {
if (lRemove + rRemove + i > s.length()) {
return;
}
if (left == -1) {
return;
}
if (s.charAt(i) == '(') {
left++;
} else if (left == ')') {
left--;
}
if (i == index || s.charAt(i) != s.charAt(i - 1)) {
if (lRemove > 0 && s.charAt(i) == '(') {
solve(s.substring(0, i) + s.substring(i + 1), i, lRemove - 1, rRemove, left - 1);
}
if (rRemove > 0 && s.charAt(i) == ')') {
solve(s.substring(0, i) + s.substring(i + 1), i, lRemove, rRemove - 1, left + 1);
}
}
}
}
public List<String> removeInvalidParentheses(String s) {
int lRemove = 0, rRemove = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
lRemove++;
} else if (s.charAt(i) == ')') {
if (lRemove == 0) {
rRemove++;
} else {
lRemove--;
}
}
}
if (lRemove == rRemove && rRemove == 0) {
return Collections.singletonList(s);
}
solve(s, 0, lRemove, rRemove, 0);
return ans;
}
private boolean isValid(String str) {
int left = 0;
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '(') {
left++;
} else if (str.charAt(i) == ')') {
left--;
if (left == -1) {
return false;
}
}
}
return left == 0;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
new Solution().removeInvalidParentheses(in.next()).forEach(System.out::println);
}
}
}