• 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 };
  • 相关阅读:
    【今日CS 视觉论文速览】Mon, 7 Jan 2019
    文章汇总页面
    【MarkDown】转义字符
    hdu 4678 Mine 博弈论
    hdu 4294 Multiple
    hdu 4291 A Short problem
    hdu 4672 Present Day, Present Time 博弈论
    hdu 3544 Alice's Game 博弈论
    hdu 3389 Game 博弈论
    hdu 2147 kiki's game 博弈论
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3547419.html
Copyright © 2020-2023  润新知