1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public String minRemoveToMakeValid(String s) { Stack<Integer> stack = new Stack<>(); char ch1 = '('; char ch2 = ')'; Set<Integer> set = new HashSet<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == ch1) { stack.push(i); } else if (ch == ch2) { if (!stack.empty()) { stack.pop(); }else { set.add(i); } } }
String ans = ""; for (int i = 0; i < s.length(); i++) { if (!stack.contains(i) && !set.contains(i)) { ans += s.charAt(i); } } return ans; } }
|