• Longest Valid Parentheses


    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    For "(()", the longest valid parentheses substring is "()", which has length = 2.

    Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

    问题描述:给定一个只包含“(”和")"的串,找出一个最长的符合规则的子串。

    对于“(()”,最长有效子串是“()”,所以长度是2

    另一个例子,“)()())”,最长的有效字串是“()()”,所以长度是4.

      解题思路:

      (1)申请一个与输入串长度相同的整型数组,初始化值全部为-1,数组和输入串有一一对应的关系;

      (2)遍历输入串遇到“(”,就将其对应位置下标入栈;

      (3)遇到“)”,就将数组对应位置的值设置为0,弹出栈中第一个值,并将整型数组对应位置置0,这样保证对应的“()”,它们在整型数组中对应的值是0;

      (4)遍历结束,寻找0的连续个数最大值,就是要求的结果。

    int longestValidParentheses(char* s) {
        int slen=strlen(s);
        if(slen<=1)return 0;
        
          int* index=(int*)malloc(sizeof(int)*slen);
          
          for(int i=0;i<slen;i++)index[i]=-1;
          
          int* stack=(int*)malloc(sizeof(int)*slen);
          int top=0;
          
          for(int i=0;i<slen;i++)
              if(s[i]=='(')stack[top++]=i;
              else{
                  if(top!=0){
                      index[stack[top-1]]=0;
                      index[i]=0;
                      top--;
                  }
              }
              
        int count=0;
        int newCount=0;
        for(int i=0;i<slen;i++)
            if(index[i]!=-1)newCount++;
            else{
                if(newCount>count){
                    count=newCount;
                    
                }
                newCount=0;
            }
        if(newCount>count)count=newCount;
        return count;
    }
    View Code
  • 相关阅读:
    刚加入博客园
    个人作业——软件工程实践总结作业
    前四次作业--个人总结
    项目选题报告(待就业六人组)
    结对第二次—文献摘要热词统计及进阶需求
    结对第一次—原型设计(文献摘要热词统计)
    第一次作业
    logback-spring.xml 配置说明
    k8s 微服务打包上传私库、部署、发布
    k8s离线安装监控Kubernetes集群
  • 原文地址:https://www.cnblogs.com/lichao-normal/p/6148596.html
Copyright © 2020-2023  润新知