题目描述:
Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return all the possible results. You may return the answer in any order.
删除字符串中不合法的括号,使得删除后的字符串是一个合法的括号,英文字符是干扰项,可以不看。
基本思路:广度优先搜索,找到删除最少括号的方案,然后再找有没有更多的解法。
思路很简单,使用输入字符串s,我们通过删除一个(或)来生成所有可能的状态,检查它们是否有效,如果在当前级别上找到有效的状态,将它们放到最终结果列表中,我们就完成了,否则,将它们添加到队列并继续到下一级别。
时间复杂度分析
最坏的情况,需要将所有括号都去除掉,寻找所有的层级
T(n) = n x C(n, n) + (n-1) x C(n, n-1) + … + 1 x C(n, 1) = n x 2^(n-1).
实际时间复杂度小于这个值
前置知识:判断一个字符串表达式是否是合法的,可以采用栈,或者简单计数法。
代码实现:
public static List<String> removeInvalidParentheses(String s) {
List<String> res = new ArrayList<>();
// sanity check
if (s == null) return res;
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
// initialize
queue.add(s);
visited.add(s);
boolean found = false;
while (!queue.isEmpty()) {
s = queue.poll();
if (isValid(s)) {
// found an answer, add to the result
res.add(s);
found = true;
}
if (found) continue;
// generate all possible states
for (int i = 0; i < s.length(); i++) {
// we only try to remove left or right paren
if (s.charAt(i) != '(' && s.charAt(i) != ')') continue;
String t = s.substring(0, i) + s.substring(i + 1);
if (!visited.contains(t)) {
// for each state, if it's not visited, add it to the queue
queue.add(t);
visited.add(t);
}
}
}
return res;
}
// helper function checks if string s contains valid parantheses
static boolean isValid(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') count++;
if (c == ')' && count-- == 0) return false;
}
return count == 0;
}