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 };
  • 相关阅读:
    Java Project和Web Project 区别
    ScannerTest-------double string
    ScannerDemo------string int
    clearfix 清除浮动的标签
    bootstrap 的布局
    <span>元素
    反省
    Django中ifequal 和ifnotequal的使用
    IndexError: list index out of range的错误原因
    python2和python3同时存在电脑时,安装包时的的命令行
  • 原文地址:https://www.cnblogs.com/easonliu/p/3637429.html
Copyright © 2011-2022 走看看