NYOJ-2-括號配對問題 棧
阿新 • • 發佈:2018-12-10
現在,有一行括號序列,請你檢查這行括號是否配對。
輸入
第一行輸入一個數N(0<N<=100),表示有N組測試資料。後面的N行輸入多組輸入資料,每組輸入資料都是一個字串S(S的長度小於10000,且S不是空串),測試資料組數少於5組。資料保證S中只含有”[“,”]”,”(“,”)”四種字元
輸出
每組輸入資料的輸出佔一行,如果該字串中所含的括號是配對的,則輸出Yes,如果不配對則輸出No
樣例輸入
3
[(])
(])
([])
樣例輸出
No
No
Yes
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; while(n--) { char str[10002]; stack<char> ok; cin>>str; int len=strlen(str); for(int i=0;i<len;i++){ if(ok.empty()){ ok.push(str[i]); }else { if(str[i]==ok.top()+1||str[i]==ok.top()+2){ ok.pop(); }else { ok.push(str[i]); } } } if(ok.empty()){ cout<<"Yes"<<endl; }else { cout<<"No"<<endl; } } return 0; }