Skip to content

Commit b8e64b0

Browse files
authored
Create minimum-remove-to-make-valid-parentheses.cpp
1 parent 88f03e8 commit b8e64b0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string minRemoveToMakeValid(string s) {
7+
unordered_set<int> lookup;
8+
int count = 0;
9+
for (auto i = 0; i < s.size(); ++i) {
10+
if (s[i] == '(') {
11+
++count;
12+
}
13+
if (s[i] == ')') {
14+
if (count) {
15+
--count;
16+
} else {
17+
s[i] = ' ';
18+
}
19+
}
20+
}
21+
if (count) {
22+
for (auto i = s.size() - 1; i >= 0; --i) {
23+
if (s[i] == '(') {
24+
s[i] = ' ';
25+
if (--count == 0) {
26+
break;
27+
}
28+
}
29+
}
30+
}
31+
s.erase(remove(s.begin(), s.end(), ' '), s.end());
32+
return s;
33+
}
34+
};

0 commit comments

Comments
 (0)