數據結構實驗之棧四:括號匹配 Time Limit: 1000MS Memory Limit: 65536KB PRoblem Description
給你一串字符,不超過50個字符,可能包括括號、數字、字母、標點符號、空格,你的任務是檢查這一串字符中的( ) ,[ ],{ }是否匹配。
Input
輸入數據有多組,處理到文件結束。
Output
如果匹配就輸出“yes”,不匹配輸出“no”
Example Input
sin(20+10)
{[}]
Example Output
yes
no
棧的思想 當出現括號的左半邊時,進棧。若出現括號右半邊時,取出棧頂元素與之比較是否匹配。最后若棧的下標回到最初則皆能匹配或無括號。
#include <bits/stdc++.h>using namespace std;int main(){ int j,top,i; char s[200],stacks[200],a; while(gets(s)!=NULL) { top=-1; for(i=0;s[i]!='/0';i++) { if(s[i]=='('||s[i]=='['||s[i]=='{') stacks[++top]=s[i]; if(s[i]==')'||s[i]==']'||s[i]=='}') { a=stacks[top]; top--; if((a=='('&&s[i]==')')||(a=='['&&s[i]==']')||(a=='{'&&s[i]=='}')) ; else break; } } if(top==-1) printf("yes/n"); else printf("no/n"); } return 0;}新聞熱點
疑難解答