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) {
string left = "([{";
string right = ")]}";
stack<char> p;
for (auto i : s) {
if (left.find(i) != string::npos) {
p.push(i);
} else {
if (p.empty() || p.top() != left[right.find(i)]) {
return false;
}
p.pop();
}
}
return p.empty();
}
};