这个题属于栈的典型题目,记得我当时学完栈后写的第一个题就是这个
首先判断,如果是三种括号的左括号就入栈;
如果是右括号,先判断栈空不空,空的直接返回false;不空的话再去判断:找到栈顶元素,如果匹配,栈顶元素出栈,不匹配返回false。
bool isValid(string s) {
// write code here
stack<char> st;
for (char c : s)
{
if (c == '(' || c == '[' || c == '{')
{
st.push(c);
}
else
{
if (st.empty())
{
return false;
}
char topChar = st.top();
if ((c == ')' && topChar == '(') ||(c == '}' && topChar == '{') ||(c == ']' && topChar == '['))
{
st.pop();
}
else
{
return false;
}
}
}
return st.empty();
}