forked from Nandinig24/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1249
42 lines (40 loc) · 1 KB
/
1249
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
38
39
40
41
42
#include <string>
#include <algorithm>
class Solution {
public:
std::string minRemoveToMakeValid(std::string s) {
int open = 0, close = 0, flag = 0;
for (char c : s) {
if (c == '(') {
open++;
flag++;
} else if (c == ')' && flag > 0) {
close++;
flag--;
}
}
int k = std::min(open, close);
std::string ans = "";
open = k;
close = k;
for (char c : s) {
if (c == '(') {
if (open > 0) {
ans += '(';
open--;
}
continue;
}
if (c == ')') {
if (close > 0 && close > open) {
ans += ')';
close--;
}
continue;
} else {
ans += c;
}
}
return ans;
}
};