From 3284c1e532b9f23cde1f3f60b03e51cb53e32b87 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Wed, 12 Feb 2025 23:04:31 +0800 Subject: [PATCH] feat: 20_valid_parentheses --- 20_valid_parentheses/main.cpp | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 20_valid_parentheses/main.cpp diff --git a/20_valid_parentheses/main.cpp b/20_valid_parentheses/main.cpp new file mode 100644 index 0000000..0d73ef4 --- /dev/null +++ b/20_valid_parentheses/main.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution { +public: + bool isValid(string s) { + stack stk; + + for (auto c : s) { + switch (c) { + case '(': + case '[': + case '{': + stk.emplace(c); + break; + case ')': + if (stk.empty() || '(' != stk.top()) { + return false; + } + stk.pop(); + break; + case ']': + if (stk.empty() || '[' != stk.top()) { + return false; + } + stk.pop(); + break; + case '}': + if (stk.empty() || '{' != stk.top()) { + return false; + } + stk.pop(); + break; + } + } + + if (!stk.empty()) { + return false; + } + + return true; + } +};