• [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 };
  • 相关阅读:
    AllowsTransparency和WebBrowser兼容性问题解决方案
    webbrowser和js交互小结
    wpf数据验证实例及常用方法小结
    Scrum 冲刺第一天
    Scrum 冲刺第二天
    1625 宝石项链 大视野评测
    1082栅栏 大视野评测
    bzoj 1606: [Usaco2008 Dec]Hay For Sale 购买干草
    1639 月度开支 大视野评测
    1650 跳石子 大视野评测
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4353719.html
Copyright © 2020-2023  润新知