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:
parent
43bcd24b2d
commit
aa6d36233b
1 changed files with 96 additions and 0 deletions
96
cpp/minimum-remove-to-make-valid-parentheses.cpp
Normal file
96
cpp/minimum-remove-to-make-valid-parentheses.cpp
Normal 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
|
Loading…
Reference in a new issue