Problem:
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.
Solution:
class Solution { public: bool isValid(string s) { stack<char> stk; for(int i=0; i<s.size(); i++){ if(isLeft(s[i])) stk.push(s[i]); else{ if(stk.empty() || !isClose(stk.top(), s[i])){ return false; } stk.pop(); } } return stk.empty(); } bool isLeft(char c){ if(c=='(' || c=='{' || c=='[') return true; return false; } bool isClose(char l, char r){ if(l=='(' && r ==')') return true; else if(l=='{' && r=='}') return true; else if(l=='[' && r==']') return true; return false; } };
Analysis:
Time complexity: O(n)
Space complexity: O(n)