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(); } };