zoukankan      html  css  js  c++  java
  • [leetcode] Longest Valid Parentheses

    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.

    思路:传统的括号匹配方法,用堆栈去匹配,遇到'('压入;遇到')',如果栈不为空,匹配成功,弹出栈顶元素,否则匹配不成功。此题需要新加一个标识数组,匹配到的位置标注为1,未匹配到的标注为0,遍历标识数组,统计连续出现1的长度,选择最长的len即为所求结果。

     1 class Solution
     2 {
     3 public:
     4   int longestValidParentheses(string s)
     5   {
     6     int size = s.size();
     7     int *is_match = new int[size];
     8     stack<char> my_stack;
     9     stack<int> temp;
    10 
    11     for(int i=0; i<size; i++)
    12     {
    13       if('(' == s[i])
    14       {
    15         my_stack.push('(');
    16         temp.push(i);
    17         is_match[i] = 0;
    18       }
    19       else
    20       {
    21         if(!my_stack.empty())
    22         {
    23           my_stack.pop();
    24           is_match[i] = 1;
    25           is_match[temp.top()] = 1;
    26           temp.pop();
    27         }
    28         else
    29           is_match[i] = 0;
    30       }
    31     }
    32 
    33     int len = 0, max = 0;
    34     for(int i=0; i<size; i++)
    35     {
    36       if(is_match[i] == 0)
    37       {
    38         max = max>len ? max : len;
    39         len = 0;
    40       }
    41       else
    42         len += is_match[i];
    43 
    44       if(i+1 == size)
    45         max = max>len ? max : len;
    46     }
    47 
    48     return max;
    49   }
    50 };
  • 相关阅读:
    Html、Vue——本地文件上传弹框+读取本地文件内容
    git-基本操作
    Selenium(二)---无界面模式+滑动底部
    Selenium(一)---Selenium的安装和使用
    Nginx+win10安装配置
    Tinghua Data Mining 9
    Tinghua Data Mining 8
    Tinghua Data Mining 7
    Tinghua Data Mining 6
    Tinghua Data Mining 5
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4353719.html
Copyright © 2011-2022 走看看