add: 220315 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-16 12:07:13 +08:00
parent aaa07a75df
commit ac6c15a295
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 48 additions and 1 deletions

47
cpp/2203/220315.cpp Normal file
View File

@ -0,0 +1,47 @@
#include <string>
#include <stack>
#include <iostream>
class Solution {
public:
static std::string minRemoveToMakeValid(const std::string& s) {
int n = s.length(), stackSize = 0;
std::stack<int> rem;
for (int i = 0; i < n; ++i) {
switch (s[i]) {
case '(':
++stackSize;
rem.push(i);
break;
case ')':
if (stackSize <= 0) {
rem.push(i);
} else {
--stackSize;
rem.pop();
}
}
}
int remSize = rem.size();
int* rems = new int[remSize];
for (int* ptr = rems + remSize - 1; !rem.empty(); ptr = ptr > rems ? ptr - 1 : ptr) {
*ptr = rem.top();
rem.pop();
}
std::string ret;
for (int p1 = 0, p2 = 0; p1 < n; ++p1) {
if (p1 == rems[p2])
++p2;
else
ret.push_back(s[p1]);
}
return ret;
}
};
int main() {
std::cout << Solution::minRemoveToMakeValid("a)b(c)d");
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220315-CN.cpp)
ADD_EXECUTABLE(2203 220315.cpp)