1249. Minimum Remove to Make Valid Parentheses
Problem
Remove the fewest parentheses from s (letters plus ( and )) so the parentheses become valid, and return any valid result.
Example: "lee(t(c)o)de)" → "lee(t(c)o)de"; "))((" → ""
Constraints: length ≤ 10⁵.
Stack the indices of unmatched (; a ) with an empty stack is invalid. Afterwards, every index still on the stack is an invalid (. Remove all invalid indices.
Complexity: O(n).
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
st, bad = [], set()
for i, ch in enumerate(s):
if ch == "(":
st.append(i)
elif ch == ")":
if st:
st.pop()
else:
bad.add(i)
bad.update(st)
return "".join(ch for i, ch in enumerate(s) if i not in bad)
assert Solution().minRemoveToMakeValid("lee(t(c)o)de)") == "lee(t(c)o)de"
assert Solution().minRemoveToMakeValid("a)b(c)d") == "ab(c)d"
assert Solution().minRemoveToMakeValid("))((") == ""
class Solution {
public String minRemoveToMakeValid(String s) {
Deque<Integer> st = new ArrayDeque<>();
boolean[] bad = new boolean[s.length()];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') st.push(i);
else if (c == ')') { if (st.isEmpty()) bad[i] = true; else st.pop(); }
}
for (int i : st) bad[i] = true;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) if (!bad[i]) sb.append(s.charAt(i));
return sb.toString();
}
}
func minRemoveToMakeValid(s string) string {
st, bad := []int{}, map[int]bool{}
for i := 0; i < len(s); i++ {
if s[i] == '(' {
st = append(st, i)
} else if s[i] == ')' {
if len(st) > 0 {
st = st[:len(st)-1]
} else {
bad[i] = true
}
}
}
for _, i := range st { // unmatched "("
bad[i] = true
}
var sb strings.Builder
for i := 0; i < len(s); i++ {
if !bad[i] {
sb.WriteByte(s[i])
}
}
return sb.String()
}