diff --git a/cpp/minimum-remove-to-make-valid-parentheses.cpp b/cpp/minimum-remove-to-make-valid-parentheses.cpp new file mode 100644 index 0000000..ca76236 --- /dev/null +++ b/cpp/minimum-remove-to-make-valid-parentheses.cpp @@ -0,0 +1,96 @@ +#include + +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 + +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