題目連結<http://acm.zjnu.edu.cn/DataStruct/showproblem?problem_id=1002>
實驗二 括弧匹配判斷演算法
| Time Limit: 1000MS |
|
Memory Limit: 65536K |
| Total Submissions: 2202 |
|
Accepted: 924 |
Description
假設在運算式中([]())或[([ ][ ])]等為正確的格式,[( ])或([( ))或 (( )])均為不正確的格式。基於棧設計一個判斷括弧是否正確匹配的演算法。
Input
輸入資料有多組,每組測試資料一行,一個字串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。
Output
對於每組測試資料,若括弧匹配輸出yes,否則輸出 no。
Sample Input []()[] ([[]])[)
Sample Output yes no
題解:
利用stack判斷儲存。從頭到尾掃描一遍字串,如果是左括弧(無論是小的還是中的)都入棧。如果是右括弧,就把當前的字元與棧的頭元素比對,如果配對就棧跳出頭元素,如果不配對,那麼就可以把標記的flag設為0。如果是右括弧,且棧內沒有元素,則flag也可為0。如果掃描已經完畢,棧內仍然存在元素,那麼flag也是0。
oj的原因多組輸入不能用~scanf("")
#include <iostream>#include <stdio.h>#include <map>#include <queue>#include <string.h>#include <string>#include <stack>using namespace std;typedef long long LL;int main(){ char s[10005]; stack<char>st; while(scanf("%s",s)!=EOF){ while(!st.empty()) st.pop(); int len=strlen(s),flag=1; for(int i=0;i<len;i++){ if(s[i]=='('||s[i]=='[') st.push(s[i]); else{ if(st.empty()){ flag=0;break; } char tmp=st.top(); st.pop(); if(s[i]==')'&&tmp=='['){ flag=0; break; } else if(s[i]==']'&&tmp=='('){ flag=0; break; } } } if(!st.empty()) flag=0; if(flag) printf("yes\n"); else printf("no\n"); } return 0;}