方法
- 先便利一遍字符串,只看字符为 ( ) 的, 用stack来抵消括号,记录非法括号的index
- 跳过非法index,构造字符串
class Solution {
public String minRemoveToMakeValid(String s) {
Stack<Integer> stack = new Stack<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(i);
} else if (c == ')') {
if (stack.isEmpty()) {
set.add(i);
} else {
stack.pop();
}
}
}
while (!stack.isEmpty()) {
set.add(stack.pop());
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (!set.contains(i)) {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}