zoukankan      html  css  js  c++  java
  • LeetCode

    Longest Valid Parentheses

    2014.2.13 02:32

    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.

    Solution:

      First of all, if you use a stack to simulate the push() and pop() operations with '(' and ')', you'll always get an empty stack at the end if the sequence is valid.

      My first reaction on this problem is an O(n^2) solution by dynamic programming. Apparently it's for subsequence, not substring, as substring is consecutive. Later I thought about O(n) dynamic programming, but no good idea came to me.

      When I tried to use a stack to simulate the sequence, I realized that the thing I pushed into the stack don't have to be the same '(', but their index.

      With the index of '(' recorded in the stack, whenever a matching with ')' happened, I can calculate the length of that matching sequence.

      The algorithm is online and one-pass, with the help of a stack and O(1) amount of extra parameters.

      Total time complexity is O(n). Space complexity is O(n) as well.

    Accepted code:

     1 // 1WA, 1AC, the simpliest solution is also the best one here.
     2 #include <algorithm>
     3 #include <stack>
     4 using namespace std;
     5 
     6 class Solution {
     7 public:
     8     int longestValidParentheses(string s) {
     9         stack<int> st;
    10         int i, len;
    11         int last_pos;
    12         int max_res;
    13         
    14         last_pos = -1;
    15         max_res = 0;
    16         len = (int)s.length();
    17         for (i = 0; i < len; ++i) {
    18             if (s[i] == '(') {
    19                 st.push(i);
    20             } else if (s[i] == ')') {
    21                 if (st.empty()) {
    22                     last_pos = i;
    23                 } else {
    24                     st.pop();
    25                     if (st.empty()) {
    26                         max_res = max(max_res, i - last_pos);
    27                     } else {
    28                         max_res = max(max_res, i - st.top());
    29                     }
    30                 }
    31             }
    32         }
    33         while (!st.empty()) {
    34             st.pop();
    35         }
    36         
    37         return max_res;
    38     }
    39 };
  • 相关阅读:
    java中的四种内部类
    09_TomCat_基础知识
    08_XML的解析_SAX解析
    IO流07_输入输出流总体系
    IO流06_处理流
    IO流05_OutputStream和Writer输出流
    IO流04_InputStream和Reader输入流
    IO流03_流的分类和概述
    IO流02_文件过滤器
    IO流01_File类
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3547419.html
Copyright © 2011-2022 走看看