题目地址:
https://www.lintcode.com/problem/2506/description
给定一个含小括号的字符串 s s s(也可能含别的字符,但不会含别的类型的括号),问至少删除多少个括号可以使得 s s s中的括号序列是合法的。返回任一删除多余括号之后的合法答案即可。
可以开一个栈存下标,当新来的右括号没有左括号匹配的时候(对应栈空)则将其标记为要删除,最后如果栈不空,将栈里的下标标记为要删除。这样就得到了所有要删除的括号的下标。代码如下:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
/**
* @param s: A string with lowercase letters and parentheses
* @return: A string which has been removed invalid parentheses
*/
public String removeParentheses(String s) {
// write your code here.
char[] chs = s.toCharArray();
Deque<Integer> stk = new ArrayDeque<>();
for (int i = 0, cnt = 0; i < chs.length; i++) {
if (chs[i] == '(') {
stk.push(i);
cnt++;
} else if (chs[i] == ')') {
if (cnt == 0) {
// 标记为空字符,表示要删除
chs[i] = ' ';
} else {
cnt--;
stk.pop();
}
}
}
while (!stk.isEmpty()) {
chs[stk.pop()] = ' ';
}
StringBuilder sb = new StringBuilder();
for (char ch : chs) {
if (ch != ' ') {
sb.append(ch);
}
}
return sb.toString();
}
}
时空复杂度 O ( l s ) O(l_s) O(ls)。