Skip to content

Create 1249. Minimum Remove to Make Valid Parentheses #449

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions 1249. Minimum Remove to Make Valid Parentheses
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution {
public:
string minRemoveToMakeValid(string s) {
int open = 0, close = 0;
string ans;
//traverse from start to end to eleminate extra closing braces
for (const char& c : s) {
if (c != '(' && c != ')') {
ans += c;
} else if (c == '(') {
open++;
ans += c;
} else if (open > 0) {
ans += c;
open--;
}
}

//traverse from end to start to remove extra opening braces
if (open > 0) {
int n = ans.length();
s = ans;
ans = "";
open = 0, close = 0;
for (int i = n - 1; i >= 0; i--) {
char c = s[i];
if (c != '(' && c != ')') {
ans += c;
} else if (c == ')') {
close++;
ans += c;
} else if (close > 0) {
ans += c;
close--;
}
}
}
else{
return ans;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
Loading