zoukankan      html  css  js  c++  java
  • 10.18T5水题刷自信

    最长匹配3526

    【问题描述】

    对一个由(,),[,],括号组成的字符串,求出其中最长的括号匹配子串。具体来说,满足如下条件的字符串成为括号匹配的字符串:

    1.(),[]是括号匹配的字符串。

    2.若A是括号匹配的串,则(A),[A]是括号匹配的字符串。

    3.若A,B是括号匹配的字符串,则AB也是括号匹配的字符串。

    例如:(),[],([]),()()都是括号匹配的字符串,而][,[(]),(]则不是。

    字符串A的字串是指由A中连续若干个字符组成的字符串。

    例如,A,B,C,ABC,CAB,ABCABC都是ABCABC的子串。空串是任何字符串的子串。

    【输入】

    输入一行,为一个仅由()[]组成的非空字符串。

    【输出】

    输出也仅有一行,为最长的括号匹配子串。若有相同长度的子串,输出位置靠前的子串。

    【样例输入1】

     ([(][()]]()

    【样例输出1】

     [()]

    【样例输入2】

     ())[]

    【样例输出2】

     ()

    【数据范围】

    对于20%的数据,字符串长度≤100。

    对于50%的数据,字符串长度≤10,000。

    对于100%的数据,字符串长度≤1,000,000。

    栈模拟

    code:

     1 #include<algorithm>
     2 #include<iostream>
     3 #include<cstring>
     4 #include<iomanip>
     5 #include<cstdlib>
     6 #include<cstdio>
     7 using namespace std;
     8 char ch[1000050];
     9 int n;
    10 int st,ed;
    11 int top,i;
    12 int Sta[10000050];
    13 int main(){
    14     ch[0]=0;
    15     gets(ch);
    16     n=strlen(ch);
    17     st=1;
    18     Sta[0]=-1;
    19     while(i<n){
    20         if(i-Sta[top]-2>ed-st){st=Sta[top]+1; ed=i-1;}
    21         if(ch[i]=='('||ch[i]=='[') Sta[++top]=i;
    22         if(ch[i]==')'){
    23             if(top!=0&&ch[Sta[top]]=='(') top--;
    24                 else Sta[top=0]=i;
    25         }
    26         if(ch[i]==']'){
    27             if(top!=0&&ch[Sta[top]]=='[') top--;
    28                 else Sta[top=0]=i;    
    29         }
    30         i++;
    31     }
    32     if(n-Sta[top]-2>ed-st){st=Sta[top]+1; ed=n-1;}
    33     if(ed-st>0){
    34         ch[ed+1]=0;
    35         printf("%s",ch+st);
    36     }
    37     return 0;
    38 }

    over

  • 相关阅读:
    MYbatis调试日记(三)
    Mybatis错误调试(二)
    【转载】MyBatis之传入参数
    Mybatis代码调试问题总结(一)
    【转载】Mybatis多参数查询映射
    未整理的资源
    Strace--系统调用分析问题集锦
    java初始化过程中成员变量
    java三元表达式编程规范问题
    转:Java的一道面试题----静态变量初始化过程
  • 原文地址:https://www.cnblogs.com/saionjisekai/p/9813194.html
Copyright © 2011-2022 走看看