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.

    Analyse: Consider scan the string from two sides. 

    Runtime: 8ms

     1 class Solution {
     2 public:
     3     int longestValidParentheses(string s) {
     4         if(s.size() <= 1) return 0;
     5         
     6         int answer = 0, start = -1, depth = 0;
     7         
     8         for(int i = 0; i < s.size(); i++){
     9             if(s[i] == '(') depth++;
    10             else{
    11                 depth--;
    12                 if(depth < 0){
    13                     start = i;
    14                     depth = 0;
    15                 }
    16                 else if(depth == 0) answer = max(answer, i - start);
    17             }
    18         }
    19         
    20         depth = 0;
    21         start = s.size();
    22         for(int i = s.size() - 1; i >= 0; i--){
    23             if(s[i] == ')') depth++;
    24             else{
    25                 depth--;
    26                 if(depth < 0){
    27                     depth = 0;
    28                     start = i;
    29                 }
    30                 else if(depth == 0) answer = max(answer, start - i);
    31             }
    32         }
    33         return answer;
    34     }
    35 };
  • 相关阅读:
    [HDU 2089]不要62
    [WC 2011]Xor
    [BJOI 2011]元素
    [NOIp 2014]解方程
    [UVa 1326]Jurassic Remains
    [BZOJ 2152]聪聪可可
    [IOI 2011]Race
    [测试题]打地鼠
    [POJ 2828]Buy Tickets
    [测试题]gene
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4665068.html
Copyright © 2011-2022 走看看