-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 1249_Minimum_Remove_to_Make_Valid_Parentheses.java
- Loading branch information
1 parent
1ad4921
commit 763f4bf
Showing
1 changed file
with
24 additions
and
18 deletions.
There are no files selected for viewing
42 changes: 24 additions & 18 deletions
42
Strings/1249_Minimum_Remove_to_Make_Valid_Parentheses.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |