假設一個算術表達式中可以包含三種括號:圓括號“(”和“)”,方括號“[”和“]”和花括號“{”和“ ”,且這三種括號可按任意的次序嵌套使用(如:…[…{… …[…]…]…[…]…(…)…)。編寫判別給定表達式中所含括號是否正確配對出現的算法。輸出結果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; }