20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
class Solution{ public: bool isValid(string str){ stack<char> S; for(auto c: str){ switch(c){ case '(': case '[': case '{': S.push(c); break; case ')': if(!S.size() || S.top() != '(') return false; else S.pop(); break; case ']': if(!S.size() || S.top() != '[') return false; else S.pop(); break; case '}': if(!S.size() || S.top() != '{') return false; else S.pop(); break; default : return false; } } return !S.size(); } };