假设一个算数表达式之中允许包含三种括号:圆括号,方括号,大括号。设计一个算法采用顺序栈判断表达式值中的括号是否正确配对。
详情见代码:
#include <iostream>
#include <stack>
using namespace std;
stack<char> op;
int Match(char exp[], int n)
{
int i = 0, tag = 1;
while (i < n&&tag == 1)
{
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
op.push(exp[i]);
if (exp[i] == ')')
{
if (op.top() == '(') op.pop();
else tag = 0;
}
if (exp[i] == ']')
{
if (op.top() == '[') op.pop();
else tag = 0;
}
if (exp[i] == '}')
{
if (op.top() == '{') op.pop();
else tag = 0;
}
i++;
}
if (!op.empty())
{
tag = 0;
}
return tag;
}