zoukankan      html  css  js  c++  java
  • [Leetcode] 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.

    很多人会说这道题用动规,可是用动规每次匹配后还要向前到上一个匹配跟这个匹配是否连接,时间复杂度为O(n^2),其实可以换个想法,用一个bool数组来标记已经匹配过的字符,找到最长的连续标记的长度就是所求的结果。只要遍历两遍数组,时间复杂度为O(n)。

     1 class Solution {
     2 public:
     3     int longestValidParentheses(string s) {
     4         bool *a = new bool[s.length()];
     5         memset(a, false, s.length());
     6         stack<int> st;
     7         for (int i = 0; i < s.length(); ++i) {
     8             if (s[i] == '(') {
     9                 st.push(i);
    10             } else if (s[i] == ')' && !st.empty()) {
    11                 a[i] = true;
    12                 a[st.top()] = true;
    13                 st.pop();
    14             }
    15         }
    16         int max_len = 0, cur_len = 0;
    17         for (int i = 0; i < s.length(); ++i) {
    18             if (a[i]) ++cur_len;
    19             else cur_len = 0;
    20             max_len = max(max_len, cur_len);
    21         }
    22         return max_len;
    23     }
    24 };
  • 相关阅读:
    N皇后问题
    SDNU1349.快速幂入门
    SDNU1522.陆历川学数学
    埃氏筛
    快速幂
    string函数
    Golang介绍以及安装
    Promise解决回调地狱(多层调用问题)
    JavaScript动画相关
    ES6简单语法
  • 原文地址:https://www.cnblogs.com/easonliu/p/3637429.html
Copyright © 2011-2022 走看看