数据结构 括号匹配的检验 C++

来源:百度知道 编辑:UC知道 时间:2024/06/23 17:12:27
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,即(【】())或【(【】【】)】等为正确的格式,【(】或(【())或(()】均为不正确的格式。
请高手用C++写出算法,先谢谢了

直接使用栈就可以了。左括号入栈,遇到右括号取栈顶元素,看是否同类匹配(都为【】或都为()),匹配则出栈,继续扫描后面的表达式,若不匹配则表达式非法。
我编写的代码如下:
#include<iostream>
#include<stack>

using namespace std;
void main()
{
int i,invalid = 0;
char a[50];
char *s=a;
stack<char> st;
st.empty();
cin>>a;
while(*s!='\0')
{
if(*s == '['|| *s == '(')
st.push(*s);
else
{
if(*s == ']')
{
if(st.top() != '[')
{
invalid = 1;
break;
}
else
st.pop();
}
if(*s == ')')
{
if(st.top()!='(')
{
invalid = 1;
break;
}
else
st.pop();
}
}
s++;
}
if(!st.empty())
invalid = 1;
if(invalid)
cout<<"invalid!"<<endl;
else
cout<&