aboutsummaryrefslogtreecommitdiff
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
commit4ee426ac7a1f7c1da1fc4cd59bb122b7029fc404 (patch)
tree0e625b67abad78b5e95f616013f9a544f3d6d9e7
parentf526f35c101484b62e833956ec44791422acd700 (diff)
downloadcrupest-4ee426ac7a1f7c1da1fc4cd59bb122b7029fc404.tar.gz
crupest-4ee426ac7a1f7c1da1fc4cd59bb122b7029fc404.tar.bz2
crupest-4ee426ac7a1f7c1da1fc4cd59bb122b7029fc404.zip
import(solutions): Add problem 20 .
-rw-r--r--works/solutions/cpp/20.cpp55
1 files changed, 55 insertions, 0 deletions
diff --git a/works/solutions/cpp/20.cpp b/works/solutions/cpp/20.cpp
new file mode 100644
index 0000000..e994e96
--- /dev/null
+++ b/works/solutions/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();
+ }
+};