diff --git a/20-valid-parentheses/driver.cpp b/20-valid-parentheses/driver.cpp new file mode 100644 index 0000000..5df6f25 --- /dev/null +++ b/20-valid-parentheses/driver.cpp @@ -0,0 +1,9 @@ +#include "soln.hpp" + +int main() { + string s = "({[[[]]]})"; + bool answer = true; + Solution soln; + cout << "Checked parentheses correctly? " << soln.test(s, answer) << endl; + return 0; +} \ No newline at end of file diff --git a/20-valid-parentheses/soln.cpp b/20-valid-parentheses/soln.cpp new file mode 100644 index 0000000..231c433 --- /dev/null +++ b/20-valid-parentheses/soln.cpp @@ -0,0 +1,42 @@ +#include "soln.hpp" + +bool Solution::isValid(string s) +{ + if (s.length() == 1) + return false; + vector bstack; + for (char c : s) + { + switch (c) + { + case '(': + case '[': + case '{': + bstack.push_back(c); + break; + case ')': + if (bstack.size() < 1 || bstack.back() != '(') + return false; + else + bstack.pop_back(); + break; + case ']': + if (bstack.size() < 1 || bstack.back() != '[') + return false; + else + bstack.pop_back(); + break; + case '}': + if (bstack.size() < 1 || bstack.back() != '{') + return false; + else + bstack.pop_back(); + break; + } + } + return bstack.size() == 0; +} + +bool Solution::test(string s, bool answer) { + return isValid(s) == answer; +} \ No newline at end of file diff --git a/20-valid-parentheses/soln.hpp b/20-valid-parentheses/soln.hpp new file mode 100644 index 0000000..655be95 --- /dev/null +++ b/20-valid-parentheses/soln.hpp @@ -0,0 +1,8 @@ +#include +using namespace std; +class Solution +{ +public: + bool isValid(string s); + bool test(string s, bool answer); +}; \ No newline at end of file