LeetCode 32 - Longest Valid Parentheses SubString


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.
X. Using stack
https://www.jianshu.com/p/392b9058f503
truly brilliant to store the index into stack (instead of the parentheses)
    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        int max=0;
        int left = -1;
        for(int j=0;j<s.length();j++){
            if(s.charAt(j)=='(') stack.push(j);            
            else {
                if (stack.isEmpty()) left=j;
                else{
                    stack.pop();//\\
                    if(stack.isEmpty()) max=Math.max(max,j-left);
                    else max=Math.max(max,j-stack.peek());
                }
            }
        }
        return max;
    }
    public int longestValidParentheses(String s) {
        LinkedList<Integer> stack = new LinkedList<>();
        int result = 0;
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ')' && stack.size() > 1 && s.charAt(stack.peek()) == '(') {
                stack.pop();
                result = Math.max(result, i - stack.peek());
            } else {
                stack.push(i);
            }
        }
        return result;
    }
}
https://discuss.leetcode.com/topic/2289/my-o-n-solution-using-a-stack/2

  • Scan the string from beginning to end.
  • If current character is '(',
    push its index to the stack. If current character is ')' and the
    character at the index of the top of stack is '(', we just find a
    matching pair so pop from the stack. Otherwise, we push the index of
    ')' to the stack.
  • After the scan is done, the stack will only
    contain the indices of characters which cannot be matched. Then
    let's use the opposite side - substring between adjacent indices
    should be valid parentheses.
  • If the stack is empty, the whole input
    string is valid. Otherwise, we can scan the stack to get longest
    valid substring as described in step 3.
  •     int longestValidParentheses(string s) {
            int n = s.length(), longest = 0;
            stack<int> st;
            for (int i = 0; i < n; i++) {
                if (s[i] == '(') st.push(i);
                else {
                    if (!st.empty()) {
                        if (s[st.top()] == '(') st.pop();
                        else st.push(i);
                    }
                    else st.push(i);
                }
            }
            if (st.empty()) longest = n;
            else {
                int a = n, b = 0;
                while (!st.empty()) {
                    b = st.top(); st.pop();
                    longest = max(longest, a-b-1);
                    a = b;
                }
                longest = max(longest, a);
            }
            return longest;
        }
    http://www.cnblogs.com/grandyang/p/4424731.html
    这里我们还是借助栈来求解,需要定义个start变量来记录合法括号串的起始位置,我们遍历字符串,如果遇到左括号,则将当前下标压入栈,如果遇到右括号,如果当前栈为空,则将下一个坐标位置记录到start,如果栈不为空,则将栈顶元素取出,此时若栈为空,则更新结果和i - start + 1中的较大值,否则更新结果和i - 栈顶元素中的较大值
    https://zxi.mytechroad.com/blog/stack/leetcode-32-longest-valid-parentheses/
      int longestValidParentheses(string s) {
        stack<int> q;
        int start = 0;
        int ans = 0;
        for (int i = 0;i < s.length(); i++) {
          if(s[i] == '(') {
            q.push(i);
          } else {
            if (q.empty()) {
              start = i + 1;
            } else {
              int index = q.top(); q.pop();
              ans = max(ans, q.empty() ? i - start + 1 : i - q.top());          
            }
          }
        }
        return ans;
      }
    The idea is simple, we only update the result (max) when we find a "pair".
    If we find a pair. We throw this pair away and see how big the gap is between current and previous invalid.
    EX: "( )( )"
    stack: -1, 0,
    when we get to index 1 ")", the peek is "(" so we pop it out and see what's before "(".
    In this example it's -1. So the gap is "current_index" - (-1) = 2.
    The idea only update the result (max) when we find a "pair" and push -1 to stack first covered all edge cases.
    Since any valid parentheses sequence starts from a '(' and ends at ')', we can calculate new length when we meet a ')'. The key is to use a stack to store all the indices and the start position is always the one on top of the stack. See the code below for details.
     // Using a stack. One pass
        int longestValidParentheses(string s) {
            vector<int> stack;
            int maxLen = 0;
            for (int i = 0; i < s.size(); ++i)
            {
                if (s[i] == '(')
                    stack.push_back(i);
                else {
                    if (!stack.empty() && s[stack.back()] == '(') {
                        stack.pop_back();
                        int lastPos = -1;
                        if (!stack.empty())
                            lastPos = stack.back();
                        int curLen = i - lastPos;
                        maxLen = (maxLen < curLen) ? curLen : maxLen;
                    } else
                        stack.push_back(i);
                }
            }
            return maxLen;
        }

    1. stack里面装的一直是“还没配好对的那些可怜的括号的index”
    2. 是'(‘的时候push
    3. 是’)’的时候,说明可能配对了;看stack top是不是左括号,不是的话,push当前右括号
    4. 是的话,pop那个配对的左括号,然后update res:i和top的(最后一个配不成对的)index相减,就是i属于的这一段的当前最长。如果一pop就整个栈空了,说明前面全配好对了,那res就是最大=i+1
    public int longestValidParentheses(String s) {
        int res = 0;
        Stack<Integer> stack = new Stack<Integer>();
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == ')' && !stack.isEmpty() && arr[stack.peek()] == '(') {
                stack.pop();
                if (stack.isEmpty())
                    res = i + 1;
                else
                    res = Math.max(res, i - stack.peek());
            } else {
                stack.push(i);
            }
        }
        return res;
    }
    解题思路:最容易想到的解法就是穷举法,计算任意两点(i到j)之间有多少个合法的()串,借助动态规划可以得到结果。算法复杂度为:O(n3)

    想要O(n)的解法需要一点技巧,栈中保存的不是‘(’而是‘(’所在的index,在此基础上也要弄清楚几种情况:
    每次来了‘(’之后,无条件压栈。如果碰到')'的话,如果栈不为空,就消除栈内剩余的'('
    第一:消除掉'('之后,如果栈内还有剩余的‘(’的话,最长的合法长度就是:maxLength = Math.max(i - (int)stack.peek() , maxLength);  也就是取:当前')'的index减去栈顶元素的index  和 原来max_length 两者的最大值。
    例如:对于这种情况:()(()(),可以正确的得出最大值为4。

    第二:消除掉')'之后,栈内没有剩余的‘(’了。此时需要引入一个新的变量start,用于表示合法括号字符串的起点。
    例如:对于这种情况:())()(),可以正确的得出最大值为4。

    start初始为-1,之后每次碰到‘)’且栈为空的时候更新为当前‘)’的index。也就是说无法消除的)之后的括号不可能再和前面的括号合并在一起计算最长序列,所以更新start。

    public int longestValidParentheses(String s) {
            if (s == null || s.length() == 0)
                return 0;
            int longestLength = 0;      // Length of the longest valid parentheses
            int start = 0;  // The start index of the possibly longest valid parentheses
            Stack<Integer> stack = new Stack<Integer>();
            // One-pass scan
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(') {   // Opening parenthesis
                    stack.push(i);          // Push its index
                } else {        // Closing parenthesis
                    if (stack.empty()) {    // No opening parenthesis to match
                        start = i + 1;      // i+1 is the start of next possibly LVP
                    } else {
                        stack.pop();    // The index of the opening parenthesis matched by s[i]
                        if (stack.empty())  // s[start...i] is matched
                            longestLength = Math.max(longestLength, i-start+1);
                        else    // s[stack.peek()] is unmatched; s[stack.peek()+1...i] is matched
                            longestLength = Math.max(longestLength, i-stack.peek());
                    }
                }
            }
            return longestLength;
        }

    This problem could be solved by linear scan as well. That is, maintain a stack, and scan the string from left to right, if it is ‘(‘, just push it (the index of this character) into the stack, if it is ‘)’, there are two cases, if the stack is NOT empty and the top is ‘(‘, then pop the stack out, get the current length of the valid sub string (current index  -  the top index in the stack after popping). Update the global maximum length if this length is larger. The second case (otherwise), we just push ‘)’ into the stack.
    The key point here is that: when we encounter a ‘)’ at position B and pop out a matched ‘(‘ at position A, we know the string between S[A, B] must be a valid Parentheses. The following code implements this idea and is accepted by the LeetCode OJ to pass this Longest Valid Parentheses:
    class Solution {
        public:
            int longestValidParentheses(string s) {
                int n = s.size();
                int len = 0;
                int tmp = 0;
    
                stack<int> stk;
                for (int i = 0; i < n; ++i) {
                    if ('(' == s[i])
                        stk.push(i);
                    else {
                        if (!stk.empty() && '(' == s[stk.top()]) {
                            stk.pop();
                            tmp = i - (stk.empty() ? -1 : stk.top());
                            len = max(len, tmp);
                        }
                        else {
                            stk.push(i);
                        }
                    }
                }
                return len;
            }
    };
    X. DP
    https://www.jianshu.com/p/72a4cecbf8c7
    https://leetcode.com/problems/longest-valid-parentheses/discuss/14133/my-dp-on-solution-without-using-stack
    I construct a array longest[], for any longest[i], it stores the longest length of valid parentheses which is end at i.

    And the DP idea is :

    If s[i] is '(', set longest[i] to 0,because any string end with '(' cannot be a valid one.

    Else if s[i] is ')'

         If s[i-1] is '(', longest[i] = longest[i-2] + 2

         Else if s[i-1] is ')' and s[i-longest[i-1]-1] == '(', longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]

    For example, input "()(())", at i = 5, longest array is [0,2,0,0,2,0], longest[5] = longest[4] + 2 + longest[1] = 6.
       int longestValidParentheses(string s) {
                if(s.length() <= 1) return 0;
                int curMax = 0;
                vector<int> longest(s.size(),0);
                for(int i=1; i < s.length(); i++){
                    if(s[i] == ')'){
                        if(s[i-1] == '('){
                            longest[i] = (i-2) >= 0 ? (longest[i-2] + 2) : 2;
                            curMax = max(longest[i],curMax);
                        }
                        else{ // if s[i-1] == ')', combine the previous length.
                            if(i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){
                                longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);
                                curMax = max(longest[i],curMax);
                            }
                        }
                    }
                    //else if s[i] == '(', skip it, because longest[i] must be 0
                }
                return curMax;
            }
    [leetcode] Longest Valid Parentheses | ()))(())..这种括号组合,最长的valid括号组合有多长
    括号题也不是只用stack才能做,这题是算长度,所以stack那种一match就俩一起pop了的方式就不适合了。求极值,一维dp最好使。
    • d[i]: 以i开头的最长valid parentheses有多长。
    • d[i] =
      • if  (str[i] == ‘)’),以右括号开头必定invalid,d[i] = 0
      • if (str[i] == ‘(‘),以左括号开头
        1. 我们想看对应的有木有右括号。因为d[i + 1]代表的sequence肯定是左括号开头右括号结尾,所以我们想catch((…))这种情况。j = i + 1 + d[i + 1],正好就是str[i]后面越过完整sequence的下一个,若是右括号,d[i] = 2 + d[i + 1]
        2. 除此之外,还有包起来后因为把后面的右括号用了而导致跟再往后也连起来了的情况,如((..))()()()。所以d[i]还要再加上j后面那一段的d[j + 1]
    这个定义和最长公共字串那题的定义类似,都是“以某个固定位置开始/结束”。看两头的方式又像palindrome。从后往前的一维dp也不常见。挺好玩的,一下复习好多东西。
    public int longestValidParentheses(String s) {
        if (s.length() == 0)
            return 0;
        int maxLen = 0;
        int[] d = new int[s.length()];
        // d[i] means substring starts with i has max valid lenth of d[i]
        d[s.length() - 1] = 0;
        for (int i = s.length() - 2; i >= 0; i--) {
            if (s.charAt(i) == ')')
                d[i] = 0;
            else {
                int j = (i + 1) + d[i + 1];
                if (j < s.length() && s.charAt(j) == ')') {
                    d[i] = d[i + 1] + 2; //(()())的外包情况
                    if (j + 1 < s.length())
                        d[i] += d[j + 1];//()()的后面还有的情况
                }
            }
            maxLen = Math.max(maxLen, d[i]);
        }
        return maxLen;
    }

    DP, Code from http://www.darrensunny.me/leetcode-longest-valid-parentheses/
    这道题可以用一维动态规划逆向求解。假设输入括号表达式为String s,维护一个长度为s.length的一维数组dp[],数组元素初始化为0。 dp[i]表示从s[i]到s[s.length - 1]最长的有效匹配括号子串长度。则存在如下关系:
    • dp[s.length - 1] = 0;
    • 从i - 2 -> 0逆向求dp[],并记录其最大值。若s[i] == '(',则在s中从i开始到s.length - 1计算s[i]的值。这个计算分为两步,通过dp[i + 1]进行的(注意dp[i + 1]已经在上一步求解):
      • 在s中寻找从i + 1开始的有效括号匹配子串长度,即dp[i + 1],跳过这段有效的括号子串,查看下一个字符,其下标为j = i + 1 + dp[i + 1]。若j没有越界,并且s[j] == ‘)’,则s[i ... j]为有效括号匹配,dp[i] =dp[i + 1] + 2
      • 在求得了s[i ... j]的有效匹配长度之后,若j + 1没有越界,则dp[i]的值还要加上从j + 1开始的最长有效匹配,即dp[j + 1]。
    public int longestValidParentheses(String s) {
        int n = s.length();
        int[] dp = new int[n];
        java.util.Arrays.fill(dp, 0);
        int max = 0;
        for (int i = n - 2; i >= 0; i--) {
          if (s.charAt(i) == '(') {
            int j = i + 1 + dp[i + 1];
            if (j < n && s.charAt(j) == ')') {
              dp[i] = dp[i + 1] + 2;
              int k = 0;
              if (j + 1 < n) {
                k = dp[j + 1];
              }
              dp[i] += k;
            }
            max = Math.max(max, dp[i]);
          }
        }
        return max;
      }
    维护一个s.length()一维数组,dp,其中dp[i]表示从索引i到末尾所组成字符串的前缀最长的有效括号组合的长度
    例如:)(),则为0,而非2;())(),为2,表示的是前面的()
    因此:dp[s.length() - 1] = 0;从后向前逆向求解dp[i],
    1. 如果s[i]=')',则显然dp[i]=0;(均不合法)
    2. 如果s[i]='(',跳过dp[i+1]这段长度从j=i+1+dp[i+1]开始(找到最长前缀的后驱),如果j没越界并且s[j]=')',正好和s[i]匹配(组成了dp[i]的合法最长前缀),则dp[i]=dp[i+1]+2;另外此时可能j之后的也可以连上,所以,可能要加上dp[j+1];
     2     public int longestValidParentheses(String s) {
     3         if(s == null || s.length() < 2) return 0;
     4         int max = 0;
     5         int[] dp = new int[s.length()];
     6         dp[s.length() - 1] = 0;
     7         for(int i = s.length() - 2; i >= 0; i--){
     8             if(s.charAt(i) == '('){
     9                 int j = i + 1 + dp[i + 1];
    10                 if(j < s.length() && s.charAt(j) == ')'){
    11                     dp[i] = dp[i + 1] + 2;
    12                 if(j + 1 < s.length()){
    13                     dp[i] += dp[j + 1];
    14                 }
    15                 }
    16             }
    17             max = Math.max(max,dp[i]);
    18         }
    19         return max;
    20     }
    https://discuss.leetcode.com/topic/35776/two-java-solutions-with-explanation-stack-dp-short-easy-to-understand
    The idea is go through the string and use DP to store the longest valid parentheses at that point.
    take example "()(())"
    i : [0,1,2,3,4,5]
    s : [( ,) ,( ,( ,) ,) ]
    DP:[0,2,0,0,2,6]
    1, We count all the ‘(‘.
    2, If we find a ‘)’ and ‘(‘ counter is not 0, we have at least a valid result size of 2. “()"
    3, Check the the one before (i - 1). If DP[i - 1] is not 0 means we have something like this “(())” . This will have DP “0024"
    4, We might have something before "(())”. Take "()(())” example, Check the i = 1 because this might be a consecutive valid string.
    public class Solution {
        public int longestValidParentheses(String s) {
            int[] dp = new int[s.length()];
            int result = 0;
            int leftCount = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(') {
                    leftCount++;
                } else if (leftCount > 0){
                    dp[i] = dp[i - 1] + 2;
                    dp[i] += (i - dp[i]) >= 0 ? dp[i - dp[i]] : 0;
                    result = Math.max(result, dp[i]);
                    leftCount--;
                }
            }
            return result;
        }
    }
    X. DP
    https://leetcode.com/articles/longest-valid-parentheses/
    We make use of a \text{dp} array where ith element of \text{dp} represents the length of the longest valid substring ending at ith index. We initialize the complete \text{dp}array with 0's. Now, it's obvious that the valid substrings must end with \text{‘)’}. This further leads to the conclusion that the substrings ending with \text{‘(’} will always contain '0' at their corresponding \text{dp} indices. Thus, we update the \text{dp} array only when \text{‘)’} is encountered.
    To fill \text{dp} array we will check every two consecutive characters of the string and if
    1. \text{s}[i] = \text{‘)’} and \text{s}[i - 1] = \text{‘(’}, i.e. string looks like ``.......()&quot; \Rightarrow
      \text{dp}[i]=\text{dp}[i-2]+2

      We do so because the ending "()" portion is a valid substring anyhow and leads to an increment of 2 in the length of the just previous valid substring's length.
    2. \text{s}[i] = \text{‘)’} and \text{s}[i - 1] = \text{‘)’}, i.e. string looks like ``.......))&quot; \Rightarrow
      if \text{s}[i - \text{dp}[i - 1] - 1] = \text{‘(’} then
      \text{dp}[i]=\text{dp}[i-1]+\text{dp}[i-\text{dp}[i-1]-2]+2
    The reason behind this is that if the 2nd last \text{‘)’} was a part of a valid substring (say sub_s), for the last \text{‘)’} to be a part of a larger substring, there must be a corresponding starting \text{‘(’} which lies before the valid substring of which the 2nd last \text{‘)’} is a part (i.e. before sub_s). Thus, if the character before sub_s happens to be \text{‘(’}, we update the \text{dp}[i] as an addition of 2 in the length of sub_s which is \text{dp}[i-1]. To this, we also add the length of the valid substring just before the term "(,sub_s,)" , i.e. \text{dp}[i-\text{dp}[i-1]-2].
    http://www.sigmainfy.com/blog/leetcode-longest-valid-parentheses.html
    Define f(i) to be the longest length of the valid parentheses ended at s[i], and only the following two cases, dp[i] could be calculated from a recursive definition, otherwise it is zero.
    1. if s[i] is ‘)’ and s[i-1] is equal to ‘(‘, then dp[i] = dp[i-2] + 2
    2. if s[i] is ‘)’ and s[i-1] is equal to ‘)’ and s[i - dp[i-1] – 1] is equal to ‘(‘, then dp[i] =  dp[i-1] + 2 + dp[i - dp[i-1] – 2]
            int longestValidParentheses(string s) {
                int n = s.size();
                int len = 0;
                vector<int> dp(n, 0);
    
                for (int i = 1; i < n; ++i) {
                    if (')' == s[i]) {
                        if ('(' == s[i-1]) {
                            dp[i] = 2;
                            if (i >= 2)
                                dp[i] += dp[i-2];
                        }
                        else {
                            int idx = i - dp[i-1] - 1;
                            if (idx >= 0 && '(' == s[idx]) {
                                dp[i] = dp[i-1] + 2;
                                if (idx > 0)
                                    dp[i] += dp[idx -1];
                            }
                        }
                    }
                    len = max(len, dp[i]);
                }
                return len;
            }
    
    状态转移方程:(为了方便,假设下面的指针都是合法的)
    1. 当s[i] = '(' 时,显然不需要处理,dp[i] = 0
    2. 当s[i] = ')' 时,此时s[i - 1] 有两种情况
    2.1 s[i - 1] = '('。表示s[i]匹配成功,要验证dp[i - 2]的状态,以判断是否可以与前面的相连
    2.2 s[i - 1] = ')'。表示s[i]并不一定能匹配成功,要验证dp[i - dp[i - 1] - 2] 的状态。
     2     public int longestValidParentheses(String s) {
     3         if(s == null || s.length() < 2) return 0;
     4         int max = 0,length = s.length();
     5         char[] sc = s.toCharArray();
     6         int[] dp = new int[length];
     7         Stack<Character> stack = new Stack<Character>();
     8         for(int i = 1; i < length; i++){
     9             if(sc[i] == '(') continue;
    10             if(sc[i - 1] == '('){
    11                 dp[i] = 2;
    12                 if(i - 2 >= 0) dp[i] += dp[i - 2];
    13             }else{
    14                 if(dp[i - 1] > 0){
    15                     int leap = dp[i - 1];
    16                     if(i - 1 - leap >= 0 && sc[i - 1 - leap] == '('){
    17                         dp[i] = dp[i - 1] + 2;
    18                         if(i - leap - 2 >= 0) dp[i] += dp[i - leap - 2];
    19                     }
    20                 }
    21             }
    22             max = Math.max(max,dp[i]);
    23         }
    24         return max;
    25     }
    http://dp2.me/blog/?p=482
        int longestValidParentheses(string s) {
            stack<int> lefts;
            int result = 0;
            int start = 0;
            for (int i = 0; i < s.length(); ++i) {
                if (s[i] == '(') {
                    lefts.push(i);
                } else if (!lefts.empty()){
                    lefts.pop();
                    if (lefts.empty()) {
                        result = max(result, i - start + 1);
                    } else {
                        result = max(result, i - lefts.top());
                    }
                } else {
                    start = i + 1;
                }
            }
            return result;
        }
    http://www.zrzahid.com/longest-valid-parenthesis/
    Better solution – O(1) Constant Space Solution
    a string becomes invalid for the first unmatched ‘)’ or the last unmatched 
    We can actually find maximum length valid substring by scanning left to right and keep counting valid pairs (increment length by 2 for each match) until we see a unmatched ‘)’. A valid pair would contribute 0 to overall count but would contribute 2 to length. So, whenever we see count == 0 this will indicate end of a local maxima. So, update global max at that point only. This will compute max substring that ends with unmatched ‘)’. This is not global max because there can be max substring with invalid ‘(‘. For example, ()())(((()). In order to find maximum substring that can have invalid ‘(‘ we can scan from right to left and do the above same counting procedure. Final global maxima would be the maximum of the two global maxima computed from both end.
    public static int longestValidParenthesis(String str, int dir){
     int start = 0;
     int end = str.length()-1;
     int openChar = '(';
     int count = 0;
     int maxLen = 0;
     int curLen = 0;
     if(dir == -1){
      start = end;
      end = 0;
      openChar = ')';
     }
     
     for(int i = start; i!=end; i+=dir){
      if(str.charAt(i) == openChar){
       count++;
      }
      else{
       //no matching left
       if(count <= 0){
        //restart
        curLen = 0;
       }
       else{
        //a local match
        count--;
        curLen += 2;
        
        if(count == 0){
         maxLen = Math.max(maxLen, curLen);
        }
       }
      }
     }
     
     return maxLen;
    }
    
    public static int longestValidParenthesis2(String str){
     return Math.max(longestValidParenthesis(str, 1), longestValidParenthesis(str, -1));
    }

    O(n) time and O(n) space
    1. Scan each character left to right
    2. If current character is '(' then this is part of current local maxima. Push the position into a stack to compute length of local of local maxima later when we see a ending parenthesis. 
    3. If current character is ')' then we have 2 cases - 
       3a. If stack is empty - this means we don't have any local maxima so we can start a new local maxima from next position by setting a start position of local maxima to the index.
       3b. If stack is not empty - this means we already have a local maxima with. So, pop out the matching '('. We have two sub cases - 
           3b.i. The stack is empty - this means we just finished a local maxima. So, we can compute length of local maxima using the start position we are maintaining, that is len = i-start. Update the global maxima. 
           3b.ii. The stack is not empty - this means we have more open parenthesis in current local maxima to match. So, we are extending a local maxima here. The start of the local maxima so far would be top of the stack. So, we compute len = i-stack.top() and update global maxima accordingly. 
    public static int longestValidParenthesis(String str){
     int maxLen = 0;
     int start = -1;
     Stack<Integer> stack = new Stack<Integer>();
     
     for(int i = 0; i<str.length(); i++){
      if(str.charAt(i) == '('){
       stack.push(i);
      }
      else{
       //no matching left
       if(stack.isEmpty()){
        start = i;
       }
       else{
        stack.pop();
        if(!stack.isEmpty()){
         maxLen = Math.max(maxLen, i-stack.peek());
        }
        else{
         maxLen = Math.max(maxLen, i-start);
        }
       }
      }
     }
     
     return maxLen;
    }
    def isValid(str) :
      int count;
    
      foreach(character c in str)
          if (c == '(') then
               count++;
          else
               if(count == 0)
                  return false;
               count--;
          end
      end
    
      return (count == 0)
    end
    X. https://discuss.leetcode.com/topic/8305/simple-java-solution
    enter image description here
    public int longestValidParentheses(String s) {
        char[] S = s.toCharArray();
        int[] V = new int[S.length];
        int open = 0;
        int max = 0;
        for (int i=0; i<S.length; i++) {
         if (S[i] == '(') open++;
         if (S[i] == ')' && open > 0) {
          V[i] = 2 + V[i-1] + (i-2-V[i-1] > 0 ? V[i-2-V[i-1]] : 0);
          open--;
         }
         if (V[i] > max) max = V[i];
        }
        return max;
    }
    https://discuss.leetcode.com/topic/22287/constant-space-o-n-time-with-forward-and-backward-pass
    When right parentheses are more than left parentheses in the forward pass, we can discard previous parentheses. In the backward pass, when left parentheses are more than right parentheses, we can discard previous parentheses.
    int longestValidParentheses(string s) {
        int longest = 0;
        int extra=0;
        int length=0;
        for(int i=0; i<s.size(); i++) {
            if(s[i] == '(') {
                extra++;
                length++;
            }
            else {
                if(extra>0) {
                    extra--;
                    length++;
                    if(extra == 0)
                        longest = max(longest, length);
                }
                else {
                    extra = 0;
                    length=0;
                }
            }
        }
        length = 0;
        extra=0;
        for(int i=s.size()-1; i>=0; i--) {
            if(s[i] == ')') {
                extra++;
                length++;
            }
            else {
                if(extra>0){
                    extra--;
                    length++;
                    if(extra == 0)
                        longest = max(longest, length);
                    
                }
                else {
                    extra = 0;
                    length=0;
                }
            }
        }
        return longest;
    }
    Also check http://yucoding.blogspot.com/2013/01/leetcode-question-46-longest-valid.html

    X. https://leetcode.com/articles/longest-valid-parentheses/
    Time complexity : O(n^3). Generating every possible substring from a string of length n requires O(n^2). Checking validity of a string of length n requires O(n).
      public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
          if (s.charAt(i) == '(') {
            stack.push('(');
          } else if (!stack.empty() && stack.peek() == '(') {
            stack.pop();
          } else {
            return false;
          }
        }
        return stack.empty();
      }

      public int longestValidParentheses(String s) {
        int maxlen = 0;
        for (int i = 0; i < s.length(); i++) {
          for (int j = i + 2; j <= s.length(); j += 2) {
            if (isValid(s.substring(i, j))) {
              maxlen = Math.max(maxlen, j - i);
            }
          }
        }
        return maxlen;

      }


    Labels

    LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

    Popular Posts