File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ string minRemoveToMakeValid(string s) {
4+ int open = 0, close = 0;
5+ string ans;
6+ //traverse from start to end to eleminate extra closing braces
7+ for (const char& c : s) {
8+ if (c != '(' && c != ')') {
9+ ans += c;
10+ } else if (c == '(') {
11+ open++;
12+ ans += c;
13+ } else if (open > 0) {
14+ ans += c;
15+ open--;
16+ }
17+ }
18+
19+ //traverse from end to start to remove extra opening braces
20+ if (open > 0) {
21+ int n = ans.length();
22+ s = ans;
23+ ans = "";
24+ open = 0, close = 0;
25+ for (int i = n - 1; i >= 0; i--) {
26+ char c = s[i];
27+ if (c != '(' && c != ')') {
28+ ans += c;
29+ } else if (c == ')') {
30+ close++;
31+ ans += c;
32+ } else if (close > 0) {
33+ ans += c;
34+ close--;
35+ }
36+ }
37+ }
38+ else{
39+ return ans;
40+ }
41+ reverse(ans.begin(), ans.end());
42+ return ans;
43+ }
44+ };
You can’t perform that action at this time.
0 commit comments