1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

cpp: add «1249. Minimum Remove to Make Valid Parentheses»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-04-07 00:15:55 +02:00
parent 43bcd24b2d
commit aa6d36233b
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,96 @@
#include <string>
class Solution {
public:
std::string minRemoveToMakeValid(std::string s) {
int open = 0;
for (auto i = 0u; i < s.size(); ++i) {
switch (s[i]) {
case '(':
// opening
++open;
break;
case ')':
if (open > 0) {
// can close
--open;
} else {
// have to remove the closing paren
s.erase(i, 1);
--i;
}
}
}
// Remove the opening brackets from end
for (auto i = s.size(); open > 0 && i-- > 0;) {
if (s[i] == '(') {
s.erase(i, 1);
--open;
}
}
return s;
}
};
#ifdef _MF_TEST
#include <gtest/gtest.h>
namespace {
bool valid(const std::string &s) {
int open = 0;
for (char c : s) {
switch (c) {
case '(':
++open;
break;
case ')':
if (open-- <= 0) {
return false;
}
break;
}
}
return open == 0;
}
} // namespace
TEST(valid, valid_strings) {
EXPECT_TRUE(valid(""));
EXPECT_TRUE(valid("(lee(t(c)o)de)"));
EXPECT_TRUE(valid("lee(t(c)o)de"));
EXPECT_TRUE(valid("(a)b(c)d"));
EXPECT_TRUE(valid("ab(c)d"));
EXPECT_TRUE(valid("(())(())"));
}
TEST(valid, invalid_strings) {
EXPECT_FALSE(valid("lee(t(c)o)de)"));
EXPECT_FALSE(valid("a)b(c)d"));
EXPECT_FALSE(valid("))(("));
}
TEST(examples, _1) {
Solution s;
EXPECT_TRUE(valid(s.minRemoveToMakeValid("lee(t(c)o)de)")));
}
TEST(examples, _2) {
Solution s;
EXPECT_TRUE(valid(s.minRemoveToMakeValid("a)b(c)d")));
}
TEST(examples, _3) {
Solution s;
EXPECT_TRUE(valid(s.minRemoveToMakeValid("))((")));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
#endif