mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
97 lines
2 KiB
C++
97 lines
2 KiB
C++
|
#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
|