第5周项目3-括号的匹配

来源:互联网 发布:手机fps显示软件 编辑:程序博客网 时间:2024/05/17 00:04

问题及代码:

/* Copyright (c)2016,烟台大学计算机与控制工程学院 All rights reserved. 文件名称:项目3.cbp 作    者:陈光辉完成日期:2016年9月29日 版 本 号:v1.0   问题描述:假设表达式中允许三种括号:圆括号、方括号和大括号。编写一个算法,判断表达式中的各种左括号是否与右括号匹配。            例如,输入2+(3+4)*[2+{[3]}]-8,输出匹配正确;输入2+(3+4*[2)+{[3]}-8,输出匹配错误。 输入描述:输入表达式 程序输出:输出判断结果 */

头文件及功能函数详见【顺序栈算法库】

main函数代码:

#include "sqstack.h"    bool isMatch(char *st)  {      int d=1, i;      char c;      SqStack *s;      InitStack(s);      for(i=0; st[i]!='\0'&&d; i++)      {          switch(st[i])          {          case'(':          case'[':          case'{':              Push(s, st[i]);              break;          case')':              Pop(s, c);              if(c!='(') d=0;              break;          case']':              Pop(s, c);              if(c!='[') d=0;              break;          case'}':              Pop(s,c);              if(c!='{') d=0;              break;          }      }      if(StackEmpty(s)&&d==1)          return true;      else          return false;  }    int main()  {        char st[50];      printf("请输入表达式:");      scanf("%s", st);      if(isMatch(st))          printf("配对正确!!\n");      else          printf("配对错误!!\n");      return 0;  }
运行结果:


知识点总结:

通过栈解决具体应用问题。


0 0
原创粉丝点击