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 match(char a, char b) {
if (a == '[' && b == ']') return true;
if (a == '(' && b == ')') return true;
if (a == '{' && b == '}') return true;
return false;
}
bool isValid(string s) {
int len = s.size();
if (len % 2 == 1) return false;
stack<char> r;
int i = 0;
r.push(s[i++]);
while (i < len) {
if (r.empty()) {
r.push(s[i++]);
continue;
}
if (match(r.top(), s[i])) {
r.pop(); i++;
} else {
r.push(s[i++]);
}
}
if (r.empty()) return true;
else return false;
}
};