|
| 1 | +// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses |
| 2 | +// T: O(n) |
| 3 | +// S: O(n) |
| 4 | + |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Set; |
| 9 | +import java.util.Stack; |
| 10 | + |
| 11 | +public class MinimumRemoveToMakeValidParentheses { |
| 12 | + private static final record OpeningBrace(int index) { } |
| 13 | + |
| 14 | + public String minRemoveToMakeValid(String s) { |
| 15 | + final Stack<OpeningBrace> stack = new Stack<>(); |
| 16 | + final List<Integer> extraClosingBraceIndices = new ArrayList<>(); |
| 17 | + char c; |
| 18 | + for (int i = 0 ; i < s.length() ; i++) { |
| 19 | + c = s.charAt(i); |
| 20 | + if (c == ')') { |
| 21 | + if (!stack.isEmpty()) { |
| 22 | + stack.pop(); |
| 23 | + } else extraClosingBraceIndices.add(i); |
| 24 | + } else if (c == '(') stack.push(new OpeningBrace(i)); |
| 25 | + } |
| 26 | + final Set<Integer> errorIndices = compileErrorIndicesFrom(extraClosingBraceIndices, stack); |
| 27 | + StringBuilder result = new StringBuilder(); |
| 28 | + for (int i = 0; i < s.length() ; i++) { |
| 29 | + if (!errorIndices.contains(i)) { |
| 30 | + result.append(s.charAt(i)); |
| 31 | + } |
| 32 | + } |
| 33 | + return result.toString(); |
| 34 | + } |
| 35 | + |
| 36 | + private Set<Integer> compileErrorIndicesFrom(List<Integer> wrongClosingBraces, Stack<OpeningBrace> openingBraces) { |
| 37 | + Set<Integer> result = new HashSet<>(); |
| 38 | + while (!openingBraces.isEmpty()) { |
| 39 | + result.add(openingBraces.pop().index); |
| 40 | + } |
| 41 | + result.addAll(wrongClosingBraces); |
| 42 | + return result; |
| 43 | + } |
| 44 | +} |
0 commit comments