NYOJ2—括号配对问题
生活随笔
收集整理的這篇文章主要介紹了
NYOJ2—括号配对问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
括號配對問題
時間限制:3000 ms ?|? 內存限制:65535 KB 難度:3 描述算法:
采用棧這種數據結構,遍歷字符串遇到'('和'['的時候放入棧中,遇到')'和']'的時候取出棧頂元素進行對應的匹配,匹配上了就出棧,直到遍歷完成,如果棧中還有剩余的元素沒有出棧,那么輸出NO否則輸出Yes
下面我們來看一下具體的代碼
1 #include <iostream> 2 #include<string.h> 3 #include<stack> 4 using namespace std; 5 int main() 6 { 7 int n; 8 cin>>n; 9 while(n--) 10 { 11 char a[10010]; 12 cin>>a; 13 int i,l; 14 l=strlen(a); 15 if(l%2==1)//字符個數為奇數則肯定不匹配 16 { 17 cout<<"No"<<endl; 18 continue; 19 } 20 stack <char> s; 21 for(i=0;i<l;i++) 22 { 23 if(a[i]=='('||a[i]=='[') 24 { 25 s.push(a[i]); 26 } 27 else 28 { 29 if(!s.empty()&&s.top()=='('&&a[i]==')') 30 { 31 s.pop(); 32 continue; 33 } 34 if(!s.empty()&&s.top()=='['&&a[i]==']') 35 { 36 s.pop(); 37 continue; 38 } 39 } 40 } 41 if(!s.empty()) 42 { 43 cout<<"No"<<endl; 44 continue; 45 } 46 else 47 { 48 cout<<"Yes"<<endl; 49 continue; 50 } 51 } 52 return 0; 53 }
若有不足和錯誤之處,歡迎兄弟們拍磚指正!!!
轉載于:https://www.cnblogs.com/yinbiao/p/8280140.html
總結
以上是生活随笔為你收集整理的NYOJ2—括号配对问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我国运营商5G投资超4016亿元:5G资
- 下一篇: 我们怎样确保从大数据计算中获得价值