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; + } +};