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:
//({()}
/*algorithm
using stack, compare current char with stack top element
if pair, continue, otherwise, if it's left char, push, otherwise, stop
*///()
//() ()[]{} (] ([)]
#define isleft(c) (c == '(' || c == '[' || c == '{')
bool isValid(string s) {
if(s.size() < 1)return true;
stack<char>stk;
unordered_map<char,char>table={{'(',')'},
{'[',']'},
{'{','}'}};
int i = 0;
while(i < s.size()){
if(stk.empty() || isleft(s[i]))
stk.push(s[i]);
else if(s[i] == table[stk.top()]){
stk.pop();
}else{
break;
}
++i;
}
return stk.empty();
}
};