From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- .../easy/others/05_valid_parentheses.cc | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 top-interview-questions/easy/others/05_valid_parentheses.cc (limited to 'top-interview-questions/easy/others/05_valid_parentheses.cc') diff --git a/top-interview-questions/easy/others/05_valid_parentheses.cc b/top-interview-questions/easy/others/05_valid_parentheses.cc new file mode 100644 index 0000000..3f6d020 --- /dev/null +++ b/top-interview-questions/easy/others/05_valid_parentheses.cc @@ -0,0 +1,41 @@ +class Solution { +public: + char matchingChar(char c) { + switch (c) { + case ')': return '('; + case '}': return '{'; + case ']': return '['; + default: throw; + } + } + + bool isValid(string s) { + // ([]) -- valid + // ([)] -- invalid + std::stack st; + for (char c : s) { + switch (c) { + case '(': + case '{': + case '[': { + st.push(c); + break; + } + case ')': + case '}': + case ']': { + const char expected = matchingChar(c); + if (st.empty() || + (st.top() != expected)) { + return false; + } + st.pop(); + break; + } + default: + throw; + } + } + return st.empty(); + } +}; -- cgit v1.2.3