forked from SjxSubham/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3703. Remove K-Balanced Substrings.cpp
More file actions
63 lines (63 loc) · 2.25 KB
/
3703. Remove K-Balanced Substrings.cpp
File metadata and controls
63 lines (63 loc) · 2.25 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public:
string removeSubstring(string s, int k) {
stack<pair<char, int>> stk;
auto f = [&]() -> void {
int cnt = 0;
int len = 0;
for(auto &I : s) {
if(I == '(' && !stk.empty() && stk.top().first == I) {
stk.top().second++;
} else if(I == '(') {
stk.push({I, 1});
len++;
}
if(I == ')' && !stk.empty() && stk.top().first == I) {
stk.top().second++;
} else if(I == ')') {
stk.push({I, 1});
len++;
}
//cout << len << endl;
if(len >= 2) {
// atleast one ( and one ) present
if(stk.top().first == ')' && stk.top().second >= k) {
// enough ')' there
// stk = ((()))())(()) , and if k = 2
auto preserve_top = stk.top();
stk.pop();
if(stk.top().first == '(' && stk.top().second >= k){
int viable = min(preserve_top.second, stk.top().second);
stk.top().second -= viable;
preserve_top.second -= viable;
if(stk.top().second == 0) {
stk.pop();
len--;
}
if(preserve_top.second == 0) {
len--;
} else {
stk.push(preserve_top);
}
} else {
stk.push(preserve_top);
}
}
}
}
if(!stk.empty() && stk.top().second == 0) {
stk.pop();
}
};
f();
string ans;
while(!stk.empty()) {
int times = stk.top().second;
while(times--)
ans.push_back(stk.top().first);
stk.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};