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.
Subscribe to see which companies asked this question
class Solution {
public:
bool isValid(string s) {
stack<char> store;
for (auto c : s) {
if (c == '(' || c == '{' || c == '[')
store.push(c);
else {
if (store.empty()) return false;
if (c == ')' && store.top() == '('){
store.pop();
}
else if (c == '}' && store.top() == '{'){
store.pop();
}
else if (c == ']' && store.top() == '['){
store.pop();
}
else
return false;
}
}
return store.empty();
}
};