Python 36 ms With Comments and Example
class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        
        example: 
        -1 0       -1      <--- STACK[-1] after stack.pop()
        (  (   ) )  (  ) )
        0  1   2 3  4  5 6 <--- INDEX
        
        2 -  0   = 2
        3 - (-1) = 4
        5 - (-1) = 6
        """
        
        stack = [-1]
        count = 0
        for i in range(len(s)):
            c  = s[i]
            
            if len(stack)==0 and c== ')': continue  #if beginning with close ignore
            if c == '(': stack.append(i); continue # if open, add to stack
            # must be a )  from now on and stack filled
            
            stack.pop() # stack must have at least one open
            if len(stack) == 0: stack.append(i); continue  
            count = max(count, i - stack[-1])
        return count
Comments (0)
No comments yet.