• zoj 2704 Brackets 用栈维护括号匹配 (8-A)


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


          

  • 相关阅读:
    仿google的suggest
    renderjs主动发起通讯
    数据库设计原则(转载)
    SqlBulkCopy批量插入
    NPOI使用word模板
    visual studio 2010与NUNIT集成调试
    bond
    linux 内核参数优化
    Linux清除用户登陆及历史命令
    nginx 常用请求
  • 原文地址:https://www.cnblogs.com/814jingqi/p/3247195.html
Copyright © 2020-2023  润新知