• [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 };
  • 相关阅读:
    docker部署spring boot并接入skywalking【探索篇】
    转载:如何处理一个CVE漏洞?
    转载:JavaScript利器分享之Proj4js
    转载:geoserver 2.18.0 跨域配置
    转载:如何实现OSM地图本地发布并自定义配图
    wsl2搭建ElasticSearch集群
    测试方法
    测试用例
    软件测试分类
    前端html
  • 原文地址:https://www.cnblogs.com/easonliu/p/3637429.html
Copyright © 2020-2023  润新知