UVA 551

来源:互联网 发布:安卓本子软件 编辑:程序博客网 时间:2024/05/18 01:11

栈的应用 括号匹配


#include <iostream>#include <string>#include <cstdio>#include <memory.h>#include <stack>using namespace std;char buf[3100];int tb[6000];bool isCloseBracket(char ch){return ch==')'||ch==']'||ch=='}'||ch=='>';}void init(){tb['[']=']';tb[']']='[';tb['(']=')';tb[')']='(';tb['{']='}';tb['}']='{';tb['<']='>';tb['>']='<';tb['[']=']';tb['('*100+'*']='*'*100+')';tb['*'*100+')']='('*100+'*';}int main(){init();while (gets(buf)&&strcmp(buf,"")){stack<int>stak;int pos=1,len=strlen(buf),flag=0;for (int i=0;i<len;++i){char c=buf[i];if(c=='('&&i+1<len&&buf[i+1]=='*'){stak.push('('*100+'*');i++;}else if(c=='*'&&i+1<len&&buf[i+1]==')'){if(stak.size()==0||tb['*'*100+')']!=stak.top()){flag=1;break;}else stak.pop();i++;}else if(tb[c]){if(isCloseBracket(c)){if(stak.size()==0||tb[c]!=stak.top()){flag=1;break;}else stak.pop();}else{stak.push(c);}}++pos;}if(stak.size()||flag)printf("NO %d\n",pos);else printf("YES\n");}return 0;}


原创粉丝点击