这是一道经典的栈的应用题,利用了栈先进后出的特点实现括号匹配
class Solution {
public:
bool ispred(char a, char b) {//如果两个字符是匹配的括号则返回ture反之false
if (a == '(' && b == ')')
return true;
if (a == '[' && b == ']')
return true;
if (a == '{' && b == '}')
return true;
return false;
}
bool isValid(string s) {
stack<char> space;//初始化栈
for (auto& c : s) {//遍历字符串
if (space.size() == 0) {//栈空则先push进去
space.push(c);
} else {
if (ispred(space.top(), c)) {//栈顶元素与字符匹配则栈顶pop
space.pop();
} else {
space.push(c);//不匹配则push新元素
}
}
}
if (space.size() == 0) {//如果最后栈空则表示匹配
return true;
} else {
return false;
}
}
};