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 };
  • 相关阅读:
    第十一周总结
    第十周总结
    实验报告(七)及第九周总结
    第六次实验及第八周总结
    第五实验报告及第七周总结
    第六周&实验四
    期末课程总结
    第十四周课程总结&实验报告(简单记事本的实现)
    第十三周课程总结
    第十二周总结
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3547419.html
Copyright © 2011-2022 走看看