From 955655bb0fd54828824f0d869b5398c111a8a097 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 4 Nov 2022 17:22:15 +0800 Subject: [PATCH] s0020 --- include/s0020_valid_parentheses.hpp | 14 +++++++++++++ src/s0020_valid_parentheses.cpp | 26 ++++++++++++++++++++++++ tests/s0020_valid_parentheses.cpp | 31 +++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 include/s0020_valid_parentheses.hpp create mode 100644 src/s0020_valid_parentheses.cpp create mode 100644 tests/s0020_valid_parentheses.cpp diff --git a/include/s0020_valid_parentheses.hpp b/include/s0020_valid_parentheses.hpp new file mode 100644 index 0000000..5f06b46 --- /dev/null +++ b/include/s0020_valid_parentheses.hpp @@ -0,0 +1,14 @@ +#ifndef S0020_VALID_PARENTHESES +#define S0020_VALID_PARENTHESES + +#include +#include + +using namespace std; + +class Solution { + public: + bool isValid(string s); +}; + +#endif diff --git a/src/s0020_valid_parentheses.cpp b/src/s0020_valid_parentheses.cpp new file mode 100644 index 0000000..9060bb7 --- /dev/null +++ b/src/s0020_valid_parentheses.cpp @@ -0,0 +1,26 @@ +#include "s0020_valid_parentheses.hpp" + +bool match(string s1, string s2) { + return s1 == "(" && s2 == ")" || + s1 == "[" && s2 == "]" || + s1 == "{" && s2 == "}"; +} + +// 直接用栈 + +bool Solution::isValid(string s) { + stack stack; + int len = s.length(); + for (int i{0}; i < len; i++) { + if (stack.empty()) { + stack.push(s.substr(i, 1)); + } else { + if (match(stack.top(), s.substr(i, 1))) { + stack.pop(); + } else { + stack.push(s.substr(i, 1)); + } + } + } + return stack.empty(); +} diff --git a/tests/s0020_valid_parentheses.cpp b/tests/s0020_valid_parentheses.cpp new file mode 100644 index 0000000..ff5bd3c --- /dev/null +++ b/tests/s0020_valid_parentheses.cpp @@ -0,0 +1,31 @@ +#include "s0020_valid_parentheses.hpp" + +#include + +TEST(Problem20, Case1) { + string i{"()"}; + bool o{true}; + Solution solution; + EXPECT_EQ(solution.isValid(i), o); +} + +TEST(Problem20, Case2) { + string i{"()[]{}"}; + bool o{true}; + Solution solution; + EXPECT_EQ(solution.isValid(i), o); +} + +TEST(Problem20, Case3) { + string i{"(]"}; + bool o{false}; + Solution solution; + EXPECT_EQ(solution.isValid(i), o); +} + +TEST(Problem20, Case4) { + string i{"(){}}{"}; + bool o{false}; + Solution solution; + EXPECT_EQ(solution.isValid(i), o); +}