良好格式序列的判断
写一个程序,它读入若干括号字符(有方括号、大括号、圆括号、尖括号、等)的一个序列,并确定该序列是否为良好格式序列。比如 { [ ( ) ( ) ] < ( ( ) ( ) ) > } 是良好格式序列;而 { ( ( < > ) ( ) ) [ ( ) } } 不是良好格式序列。(利用栈结构来实现判断)
分析:对括号序列自左至右地进行扫描,用一个栈存放所扫描到的括号,若扫描到开括号 ‘{’, ‘[’, ‘<’, ‘(’ 时,则让其进栈;若扫描到开括号 ‘}’, ‘]’, ‘>’, ‘)’ 时,则检查栈顶元素是否与它匹配,若匹配,则退出栈顶元素;若不匹配,则输出不匹配的信息。若到扫描完毕时,栈已退空,则括号序列是良好的格式序列。
源程序如下:
#include <iostream.h> #define max 100 // 栈的深度 char a[max]; // 栈 int top; // 栈顶指针 int good; // 判断的结果 int match(char x,char y) { int result=0; switch(x){ case '{': if(y=='}') result=1; break; case '[': if(y==']') result=1; break; case '(': if(y==')') result=1; break; case '<': if(y=='>') result=1; break; } return result; } void push(char x) // 出栈操作 { top++; a[top]=x; } void pop(char x) // 退栈操作 { if(!match(a[top],x)) good=0; else top--; } void main(void) { char ch; top=0; good=1; cout<<"Please input character string (use 'e' to denote the end of string):"<<endl; cin>>ch; while((ch!='e')&&good){ if((ch=='{')||(ch=='[')||(ch=='(')||(ch=='<')) push(ch); else if((ch=='}')||(ch==']')||(ch==')')||(ch=='>')) pop(ch); cin>>ch; } if(good) cout<<"Good!"<<endl; else cout<<"Not Good!"<<endl; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论