forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinimumRemovetoMakeValidParentheses.java
More file actions
37 lines (33 loc) · 1006 Bytes
/
MinimumRemovetoMakeValidParentheses.java
File metadata and controls
37 lines (33 loc) · 1006 Bytes
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
32
33
34
35
36
37
class Solution {
// TC : O(n)
// SC :O(n) => "))(("
public String minRemoveToMakeValid(String s) {
Stack<Pair<Character, Integer>> st = new Stack<>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c == ')' || c == '('){
if(st.empty()){
st.push(new Pair<>(c, i));
} else{
if(c == ')' && st.peek().getKey() == '('){
st.pop();
} else{
st.push(new Pair<>(c, i));
}
}
}
}
Set<Integer> indexesToBeRemoved = new HashSet<>();
while(!st.empty()){
indexesToBeRemoved.add(st.peek().getValue());
st.pop();
}
String ans = "";
for(int i=0;i<s.length();i++){
if(!indexesToBeRemoved.contains(i)){
ans += s.charAt(i);
}
}
return ans;
}
}