2134資料結構實驗之棧四:括號匹配
阿新 • • 發佈:2019-02-08
Time Limit: 1000MS Memory limit: 65536K
題目描述
給你一串字元,不超過50個字元,可能包括括號、數字、字母、標點符號、空格,你的任務是檢查這一串字元中的( ) ,[ ],{ }是否匹配。輸入
輸入資料有多組,處理到檔案結束。輸出
如果匹配就輸出“yes”,不匹配輸出“no”示例輸入
sin(20+10) {[}]
示例輸出
yes no
提示
#include<string.h> #include<stdlib.h> #include<iostream> #include<stack> using namespace std; int match(char a[]) { stack<char>s; int n=strlen(a); for(int i=0;i<n;i++) { switch (a[i]) { case'[': case'(': case '{': case')':if(!s.empty()&&s.top()=='(') s.pop(); else return 0;break; case'}':if(!s.empty()&&s.top()=='{') s.pop(); else return 0;break; case']':if(!s.empty()&&s.top()=='[') s.pop(); else return 0;break; } } if(s.empty()) return 1; else return 0; } int main() { char a[55]; while(gets(a)) { int o=match(a); if(o==0) cout<<"no"<<endl; else cout<<"yes"<<endl; } return 0; }