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.
This is a classical case for the usage of stack.
1. when '(', '{' or '[', push into the stack.
2. otherwise, if the stack is empty, then occurs mismatching, return false. or, if the element in the top of the stack mismatch with s[i], then return false. otherwise pop the stack.
3. finally we should check if the stack is empty, if not, return false.
runtime:
source code:
bool isValid(string s) {
stack<char> chstack;
for(int i=0; i<s.size(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{') {
chstack.push(s[i]);
} else {
if(chstack.empty()) { return false; }
switch(s[i]) {
case ']':
if(chstack.top() != '[') {return false;} break;
case '}':
if(chstack.top() != '{') {return false;} break;
case ')':
if(chstack.top() != '(') {return false;} break;
default :
break;
}
chstack.pop();
}
}
if( !chstack.empty() ) return false;
else return true;
}