zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    MySQL 82 张图带你飞
    Docker一个优秀的应用容器
    大数据架构基础知识
    浏览器复杂吗
    5 分钟学懂 SSH 隧道技术
    图解数据分析如何驱动决策
    3D可视化管理推进能源革命
    一文全面解读B端产品和C端产品的差异
    智慧农业解决方案
    Win10删除右键多余选项菜单
  • 原文地址:https://www.cnblogs.com/lichao-normal/p/6148596.html
Copyright © 2011-2022 走看看