題目地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2704
題解: 1 看見括弧匹配自然想到用棧去匹配,但是這裡想記錄最大長度,想法就是每次匹配以後還要知道匹配的括弧在原來的序列中的下標,這樣把括弧存在結構體裡最好了。
2 得到了匹配的序列以後,求最大的連續的“1”序列, 記得在最後面加上一個0,否則可能漏掉最後一段連續的“1”。
3輸出子序列時,由於有可能完全沒有匹配的,於是還設定一個bool non,如果沒有一個“1”就直接輸出空串。
#include<iostream>#include<stack>#include<string>using namespace std;struct bracket{ int id; char ch;};int main(){ string s; while(cin>>s) { int size=s.length(); bracket * p=new bracket[size]; for(int i=0;i<size;i++) { p[i].ch=s[i]; p[i].id=i; } stack<bracket> st; int * ismatch=new int [size+1]; for(int i=0;i<size;i++) ismatch[i]=0; for(int i=0;i<size;i++) { if(st.empty()==true) st.push(p[i]); else { if(st.top().ch=='('&&p[i].ch==')' || st.top().ch=='['&&p[i].ch==']') { ismatch[st.top().id]=1; ismatch[i]=1; st.pop(); } else st.push(p[i]); } } int maxlength=0; int count=0; int end=0; bool non=true; ismatch[size]=0; // 處理最後一位是1的情況 for(int i=0;i<size+1;i++) { if(ismatch[i]==1) { count++; non=false; } else { if(count>maxlength) { maxlength=count; end=i-1; } count=0; } } if(non==false) cout<<s.substr(end-maxlength+1,maxlength)<<endl; else cout<<endl; cout<<endl; }}