Skip to content

Commit

Permalink
Create leetcode1249_my_version_20220220.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
allpasscool committed Feb 21, 2022
1 parent 02ab251 commit 3f3c341
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions leetcode1249/leetcode1249_my_version_20220220.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
class Solution
{
public:
string minRemoveToMakeValid(string s)
{
vector<char> newS;
int count = 0;

// remove invalid )
for (char c : s)
{
if (c == ')')
{
if (count == 0)
continue;
else
{
count--;
newS.push_back(c);
}
}
else if (c == '(')
{
count++;
newS.push_back(c);
}
else
newS.push_back(c);
}

count = 0;
// remove invalid (
for (int i = newS.size() - 1; i >= 0; i--)
{
if (newS[i] == '(')
{
if (count == 0)
newS[i] = 'X';
else
{
count--;
}
}
else if (newS[i] == ')')
{
count++;
}
}

string ans;
for (int i = 0; i < newS.size(); i++)
{
if (newS[i] != 'X')
ans += newS[i];
}

return ans;
}
};

// Runtime: 24 ms, faster than 78.26% of C++ online submissions for Minimum Remove to Make Valid Parentheses.
// Memory Usage: 12.3 MB, less than 17.02% of C++ online submissions for Minimum Remove to Make Valid
// time complexity: O(n)
// space complexity: O(n)

0 comments on commit 3f3c341

Please sign in to comment.