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) {
if (s.empty())
return true;
stack <char> m_c;
int count = s.length();
for (int i = 0; i < count; i++)
{
if(!m_c.empty())
if ((s[i] == ')' && m_c.top() == '(')
|| (s[i] == ']' && m_c.top() == '[')
|| (s[i] == '}' && m_c.top() == '{'))
{
m_c.pop();
continue;
}
m_c.push(s[i]);
}
if (m_c.empty())
return true;
else
return false;
}
};