首页 > 代码库 > 栈(括号匹配)
栈(括号匹配)
假设一个算术表达式中可以包含三种括号:圆括号“(”和“)”,方括号“[”和“]”和花括号“{”和“ ”,且这三种括号可按任意的次序嵌套使用(如:…[…{… …[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的算法。输出结果YES 或者 NO。
Input
5+{[2X5]+2}
Output
YES
Sample Input
8-[{2+7]}
Sample Output
NO
#include<iostream> #include<stack> #include<cstring> #include<cstdio> using namespace std; int main() { stack<char> s; char a[10000]={0},t; int l; gets(a); l=strlen(a); for(int i=0;i<=l-1;++i) { if(a[i]==‘(‘||a[i]==‘[‘||a[i]==‘}‘) { s.push(a[i]); } if(a[i]==‘)‘) { t=s.top(); if(t==‘(‘) s.pop(); else { cout<<"NO"<<endl; return 0; } } if(a[i]==‘]‘) { t=s.top(); if(t==‘[‘) s.pop(); else { cout<<"NO"<<endl; return 0; } } if(a[i]==‘}‘) { t=s.top(); if(t==‘{‘) s.pop(); else { cout<<"NO"<<endl; return 0; } } } cout<<"YES"<<endl; return 0; }
栈(括号匹配)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。