問題 B: Problem E
阿新 • • 發佈:2019-01-24
題目描述
請寫一個程式,判斷給定表示式中的括號是否匹配,表示式中的合法括號為”(“, “)”, “[", "]“, “{“, ”}”,這三個括號可以按照任意的次序巢狀使用。
輸入
有多個表示式,輸入資料的第一行是表示式的數目,每個表示式佔一行。
輸出
對每個表示式,若其中的括號是匹配的,則輸出”yes”,否則輸出”no”。
樣例輸入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
樣例輸出
yes
no
no
no
#include <cstdio> #include <stack> #include <string> #include <iostream> using namespace std; stack<char> s; bool judge(string str){ for(int i=0;i<str.length() ;i++){ if(str[i]=='('||str[i]=='['||str[i]=='{') s.push(str[i]) ; if(str[i]==')'||str[i]==']'||str[i]=='}'){ if(str[i]==')'){ if(!s.empty() && s.top()=='('){ s.pop() ; } else return false; } else if(str[i]==']'){ if(!s.empty() &&s.top()=='['){ s.pop() ; } else return false; } else if(str[i]=='}'){ if(!s.empty() &&s.top()=='{'){ s.pop() ; } else return false; } } } if(s.empty()) return true; return false; } int main(){ int m; scanf("%d",&m); getchar(); while(m--){ string str; getline(cin,str); while(!s.empty() ) s.pop() ; if(judge(str)==true) printf("yes\n"); else printf("no\n"); } return 0; }