数据结构-栈(括号匹配问题)

问题引入;表达式中每一个左括号都会和一个右括号相匹配,不然就会报错;
当读一串表达式例如(a+b)*c+(d-p)
利用栈存储特点(先进后出)在对上面表达式进行读取的时候,有以下步骤

读取时:
1)遇到左括号``就入栈
2)遇到右括号``且栈非空就从栈中弹出一个左括号``与其匹配
   若栈空则右括号')'多
全部读取完:
3)对栈进行判断若非空则左括号'('多
  若栈空则括号匹配

在这里插入图片描述

#include<iostream>
using namespace std;
class Matcher{
public:
     Matcher(string str);
    ~Matcher();
    int Match();
private:
     string str;
  };
Matcher::Matcher(string str){
this->str=str;} //构造函数
Matcher::~Matcher(){};
int Matcher::Match(){
	char s[10];       //定义顺序栈
	int i,top=-1;
	for(i=0;str[i]!='\0';i++)
	{
	   if(str[i]==')')
	   {
	      if(top>-1) top--;
	      else return -1;//如果栈空
	    }
	else if(str[i]=='(')
	    s[++top]=str[i];
	}
	if(top==-1) return 0;
	else return 1;
}
int main()
{string str;
cout<<"输入表达式"<<endl;
cin >> str;
Matcher m(str);
int k=m.Match();
if(k==0)cout << "括号匹配" << endl;
else if(k==1)cout << "左括号多" << endl;
else cout << "右括号多" << endl;}

在这里插入图片描述
(2020/10/17)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值