解题思路:
在表达式括号配对时返回true,否则返回false。设置一个链栈st,扫描表达式exp,遇到左括号时进栈,遇到右括号时若栈顶为左括号,则出栈,否则返回false。当表达式扫描完毕,栈为空时返回true,否则返回false。算法如下:
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
#define MaxSize 60
typedef char ElemType;
typedef struct {
ElemType data[MaxSize];
int top; //栈顶指针
}SqStack; //定义顺序栈类型
//初始化栈
void InitStack(SqStack *&s){
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
//销毁栈
void DestroyStack(SqStack *&s){
free(s);
}
//判空
bool StackEmpty(SqStack *s){
return(s->top==-1);
}
//进栈
bool Push(SqStack *&s,ElemType e){
if(s->top==MaxSize-1) //进栈判满
return false;
s->top++; //指针加一
s->data[s->top]=e;
return true;
}
//出栈
bool Pop(SqStack *&s,ElemType &e){
if(s->top==-1) //出栈判空
return false;
e=s->data[s->top]; //取栈顶元素
s->top--; //指针减一
return true;
}
//取栈顶元素,注意,与出栈的差别仅仅是指针是否减一
bool GetTop(SqStack *s,ElemType &e){
if(s->top==-1)
return false;
e=s->data[s->top];
return true;
}
//判断一个表达式括号是否配对
bool match(string exp){
SqStack *st;
InitStack(st); //初始化
char e;
int i=0;
bool match=true; //先假设它是配对的
while(i<exp.length() && match){
if(exp[i]=='(') //如果是"(",进栈
Push(st,exp[i]);
else if(exp[i]==')'){ //否则是")",出栈并比对
if(GetTop(st,e)==true){
if(e!='(')
match=false;
else
Pop(st,e); //出栈
}
else
match=false; //无法取栈顶元素表示不匹配
}
i++; //除"("和")"外的字符跳过
}
if(!StackEmpty(st))
match=false;
DestroyStack(st); //销毁
return match;
}
int main(){
string exp;
cout<<"exp:";
//注意,输入的括号应为英文状态下的,因为在进行判定的时候,我们用的英文状态下的
cin>>exp;
bool flag;
//判断表达式中的括号是否配对
flag=match(exp);
if(flag)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
注意:输入的时候请选择英文状态下的“()”输入