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 };
  • 相关阅读:
    (unix domain socket)使用udp发送>=128K的消息会报ENOBUFS的错误
    HTTP KeepAlive模式
    Windows 7 中的 God Mode
    我的开发环境配置经验
    C#格式化数值结果表(格式化字符串)
    我可怜的笔记本电脑
    JetBrains ReSharper 5.x 注册机
    异常处理准则
    调用 Windows 7 中英文混合朗读
    oracle笔记(2010130)
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4353719.html
Copyright © 2011-2022 走看看