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 };
  • 相关阅读:
    CF1439E
    CF1446
    CSP2020 游记
    CF1442
    CF1444E
    CF1444
    CF850F Rainbow Balls
    A
    uoj266[清华集训2016]Alice和Bob又在玩游戏(SG函数)
    loj536「LibreOJ Round #6」花札(二分图博弈)
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4665068.html
Copyright © 2011-2022 走看看