20. Valid Parentheses
View on LeetCode ↗
C++
class Solution {public: bool isValid(string s) { stack<char> character_stack{}; if (s.size() % 2 == 1) return false; for (int i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { character_stack.push(s[i]); } else if (s[i] == '}') { if (character_stack.size() == 0 || character_stack.top() != '{') { return false; } else { character_stack.pop(); } } else if (s[i] == ')') { if (character_stack.size() == 0 || character_stack.top() != '(') { return false; } else { character_stack.pop(); } } else if (s[i] == ']') { if (character_stack.size() == 0 || character_stack.top() != '[') { return false; } else { character_stack.pop(); } } } if (character_stack.size() != 0) return false; return true; }};
a little bit more lines of code than needed but simple stack problem. just push and pop chars with checking from stack.