删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
示例 1:
输入: “()())()”
输出: ["()()()", “(())()”]
示例 2:
输入: “(a)())()”
输出: ["(a)()()", “(a())()”]
示例 3:
输入: “)(”
输出: [""]
思路: 广度优先 BFS
/*
* 广度优先 BFS
* */
public List<String> removeInvalidParentheses(String s) {
List<String> res = new ArrayList<>();
if (s == null)
return res;
if (s.length() == 0) {
res.add("");
return res;
}
Queue<String> queue = new LinkedList<>();
Set<String> set = new HashSet<>();
queue.offer(s);
set.add(s);
boolean bl = false;
while (!queue.isEmpty()) {
String curStr = queue.poll();
if (isTrue(curStr)) {
res.add(curStr);
bl = true;
}
if (bl)
continue;
for (int i = 0; i < curStr.length(); i++) {
if (curStr.charAt(i) != '(' && curStr.charAt(i) != ')')
continue;
String str1 = curStr.substring(0, i);
String str2 = curStr.substring(i + 1);
String str3 = str1 + str2;
if (!set.contains(str3)) {
queue.offer(str3);
set.add(str3);
}
}
}
return res;
}
private boolean isTrue(String str) {
if (str == null || str.length() == 0)
return true;
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '(')
count++;
if (str.charAt(i) == ')')
count--;
if (count < 0)
return false;
}
return count == 0;
}