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 s) {
stack<char> c;
int len=s.length();
c.push(s[0]);
char tmp=c.top();
for(int i=1;i<len;i++){
if(tmp=='(' && s[i]==')'){
c.pop();
if(!c.empty()) tmp=c.top();
continue;
}
if(tmp=='{' && s[i]=='}'){
c.pop();
if(!c.empty()) tmp=c.top();
continue;
}
if(tmp=='[' && s[i]==']'){
c.pop();
if(!c.empty()) tmp=c.top();
continue;
}
c.push(s[i]);
tmp=s[i];
}
if(c.empty()) return true;
else return false;
}
};