zoj 2704 Brackets 用棧維護括弧匹配 (8-A)

來源:互聯網
上載者:User

題目地址: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;  }}

      

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.