括号配对问题

来源:互联网 发布:淘宝旧版本5.7.2下载 编辑:程序博客网 时间:2024/05/16 08:06

利用堆栈的原理进行括号的配对,具体算法可以发email问我:jingweih@usc.edu

或者留言啦~才开始练习可以多和大家切磋~

Mark:April 6th,2014 USC

#include<iostream>#include<stdio.h>using namespace std;class stack{char sign[100000];int top;public:stack():top(-1){};void pushstack(char);void popstack();void Initilizestack();char topstack();bool isempty();};void stack::pushstack(char s){sign[++top]=s;}void stack::popstack(){top--;}void stack::Initilizestack(){   top=-1;}char stack::topstack(){return sign[top];}bool stack::isempty(){if(top==-1)return true;elsereturn false;}int main(){ int num; bool flag=true; cin>>num; getchar(); stack s; for(int i=0;i<num;i++) {   s.Initilizestack();     flag=true; char line; while((line=getchar())!='\n') { if(line=='['||line=='(')                  s.pushstack(line); else if(line==']') { if(s.topstack()!='['||s.isempty()==true) flag=false; else s.popstack(); } else if(line==')') { if(s.topstack()!='('||s.isempty()==true) flag=false; else s.popstack(); } } if(flag==true) cout<<"Yes"<<endl; else cout<<"No"<<endl; }}


0 0