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> q;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
q.push(s[i]);
}
else {
if (q.size() == 0) return false;
else {
if (q.top() == '('&&s[i] == ')' || q.top() == '['&&s[i] == ']' || q.top() == '{'&&s[i] == '}') {
q.pop();
}
else return false;
}
}
}
if (q.size() == 0) return true;
else return false;
}
};