-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create leetcode1249_my_version_20220220.cpp
- Loading branch information
1 parent
02ab251
commit 3f3c341
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |