-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-1249.cpp
More file actions
37 lines (34 loc) · 898 Bytes
/
Problem-1249.cpp
File metadata and controls
37 lines (34 loc) · 898 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
// Problem - 1249
// https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
// O(n) time complexity and O(n) space complexity solution using stack
class Solution {
public:
string minRemoveToMakeValid(string s) {
unordered_set <int> us;
stack <int> st;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '(') {
st.push(i);
}
else if(s[i] == ')') {
if(st.empty()) {
us.insert(i);
}
else {
st.pop();
}
}
}
while(!st.empty()) {
us.insert(st.top());
st.pop();
}
string ans;
for(int i = 0; i < s.length(); i++) {
if(!us.count(i)) {
ans += s[i];
}
}
return ans;
}
};