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.
Code:
<span style="font-size:14px;">class Solution {
public:
bool isValid(string s) {
const int length = s.size();
stack<char> stk;
for (int i = 0; i < length; ++i) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
stk.push(s[i]);
else if (s[i] == ')' && !stk.empty() && stk.top() == '(')
stk.pop();
else if (s[i] == ']' && !stk.empty() && stk.top() == '[')
stk.pop();
else if (s[i] == '}' && !stk.empty() && stk.top() == '{')
stk.pop();
else
return false;
}
return stk.empty();
}
};</span>