bool judge(const string& temp, stack<char>& test)
{
int i =0;
char stack_pop_char;
while(i < temp.size() )
{
//遍历字符串,左括号和其他字符入栈,其他类型字符出栈
if(temp[i] =='(' || temp[i] == '[' || temp[i] == '{')
{
test.push(temp[i]);
}
if(temp[i] == ')' || temp[i] == ']' || temp[i] == '}')
{
if(test.size() > 0) //需要判断栈是否非空,为空则不能进行出栈,直接返回False
{
stack_pop_char = test.top();
test.pop();
switch(temp[i])
{
case ')':
if (stack_pop_char == '('){
continue;
}
else return false;
case ']':
if (stack_pop_char == '['){
continue;
}
else return false;
case '}':
if (stack_pop_char == '{'){
continue;
}
else return false;
}
}
else return false;
}
++i;
}
return true;
}
括号匹配问题利用了从左往右遍历字符串时,栈顶的左括号离当前位置最近的特性完成工作。栈还有一个更为出名的应用表达式的求值