summaryrefslogtreecommitdiff
path: root/cpp/20.cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-08-17 20:49:29 +0800
committercrupest <crupest@outlook.com>2020-08-17 20:49:29 +0800
commitc69f5d2153b880762931a29c5eec8188e2aa25ed (patch)
tree7d8fce442ce9cff2c1f5eb622afe93337c02df34 /cpp/20.cpp
parente027c0c482539aa0e272083f056d2d053746c390 (diff)
downloadsolutions-c69f5d2153b880762931a29c5eec8188e2aa25ed.tar.gz
solutions-c69f5d2153b880762931a29c5eec8188e2aa25ed.tar.bz2
solutions-c69f5d2153b880762931a29c5eec8188e2aa25ed.zip
Add problem 20 .
Diffstat (limited to 'cpp/20.cpp')
-rw-r--r--cpp/20.cpp55
1 files changed, 55 insertions, 0 deletions
diff --git a/cpp/20.cpp b/cpp/20.cpp
new file mode 100644
index 0000000..e994e96
--- /dev/null
+++ b/cpp/20.cpp
@@ -0,0 +1,55 @@
+#include <string>
+
+using std::string;
+
+#include <stack>
+
+class Solution
+{
+public:
+ inline static char get_companion(char c)
+ {
+ switch (c)
+ {
+ case ')':
+ return '(';
+ case ']':
+ return '[';
+ default:
+ return '{';
+ }
+ }
+
+ bool isValid(string s)
+ {
+ std::stack<char> stack;
+
+ for (const auto c : s)
+ {
+ switch (c)
+ {
+ case '(':
+ case '[':
+ case '{':
+ {
+ stack.push(c);
+ break;
+ }
+ case ')':
+ case ']':
+ default:
+ {
+ if (stack.empty())
+ return false;
+ const auto top = stack.top();
+ const char companion = get_companion(c);
+ if (top != companion)
+ return false;
+ stack.pop();
+ }
+ }
+ }
+
+ return stack.empty();
+ }
+};