From 1966190066ac1d14314039294c66e192da2cd66b Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sat, 6 Apr 2024 19:33:09 +0530 Subject: [PATCH] Create 1249. Minimum Remove to Make Valid Parentheses --- .... Minimum Remove to Make Valid Parentheses | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 1249. Minimum Remove to Make Valid Parentheses diff --git a/1249. Minimum Remove to Make Valid Parentheses b/1249. Minimum Remove to Make Valid Parentheses new file mode 100644 index 0000000..fe9ad21 --- /dev/null +++ b/1249. Minimum Remove to Make Valid Parentheses @@ -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; + } +};