Skip to content

Commit

Permalink
Update 1249_Minimum_Remove_to_Make_Valid_Parentheses.java
Browse files Browse the repository at this point in the history
  • Loading branch information
seanprashad committed May 8, 2021
1 parent 1ad4921 commit 763f4bf
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions Strings/1249_Minimum_Remove_to_Make_Valid_Parentheses.java
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
class Solution {
public String minRemoveToMakeValid(String s) {
if (s == null || s.length() == 0) { return new String(); }

if (s == null || s.isEmpty()) {
return "";
}

StringBuilder sb = new StringBuilder();
Stack<Integer> st = new Stack<>();
Set<Integer> invalidIndices = new HashSet<>();

int counter = 0;

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if (c == '(') { st.push(i); }
else if (c ==')') {
if (st.isEmpty()) { invalidIndices.add(i); }
else { st.pop(); }

if (c == '(') {
++counter;
} else if (c == ')') {
if (counter == 0) {
continue;
}
--counter;
}
}

while (!st.isEmpty()) { invalidIndices.add(st.pop()); }

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);

if (invalidIndices.contains(i)) { continue; }
sb.append(c);
}


for (int i = sb.length() - 1; i >= 0; i--) {
char c = sb.charAt(i);

if (c == '(' && counter > 0) {
--counter;
sb.deleteCharAt(i);
}
}

return sb.toString();
}
}

0 comments on commit 763f4bf

Please sign in to comment.