class Solution
{
private:
stack<char> stk;
public:
bool isValid(string s)
{
if (s.size() % 2 == 1)
{
return false;
}
for (auto ch : s)
{
if (ch == '(' || ch == '[' || ch == '{')
{
stk.push(ch);
}
else if (stk.empty() == false)
{
if (stk.top() == '(' && ch == ')')
{
stk.pop();
}
else if (stk.top() == '[' && ch == ']')
{
stk.pop();
}
else if (stk.top() == '{' && ch == '}')
{
stk.pop();
}
else
{
return false;
}
}
else
{
return false;
}
}
return stk.empty();
}
};
这里没有用到unordered_map容器,而是纯手写的判断
时间复杂度:O(n)
空间复杂度:O(n)