C++:
class Solution {
public:
bool isValid(string s) {
std::stack<char> charStack;
for ( int i = 0; i < s.size(); ++i ) {
if ( s[i] == '(' || s[i] == '{' || s[i] == '[' ) {
charStack.push( s[i] );
} else if ( s[i] == ')' || s[i] == '}' || s[i] == ']' ) {
if ( charStack.empty() ) {
return false;
}
if ( ( s[i] == ')' && charStack.top() == '(' ) ||
( s[i] == '}' && charStack.top() == '{' ) ||
( s[i] == ']' && charStack.top() == '[' ) ) {
charStack.pop();
continue;
}
return false;
}
}
return charStack.empty();
}
};