#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
32:longest Valid Parentheses
https://oj.leetcode.com/problems/longest-valid-parentheses/
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 are "()", which has length = 2.
Another example is ") () ()", where the longest valid parentheses substring are "() ()", which has length = 4.
===comments by dabay===
Use a stack to record the position of the left parenthesis ' (');
Start to record the starting position of the closed parenthesis before the opening. That is, when the opening parenthesis is actually matched, the closing parenthesis is calculated to the length of the start.
For example: the string "() ()", when traversing to the second "(", the actual position of the stack is 0 instead of 2.
When you encounter the closing parenthesis ' (',
The number I and start small is counted into the stack, and the start update points to the next position of I.
When the opening parenthesis ') ' is encountered,
If the stack is not empty,
Out of the stack, calculate if you need to update Max_so_far
Also, update start to the number of the stack
If the stack is empty,
Start points to the next position of I
‘‘‘
Class Solution:
# @param s, a string
# @return An integer
def longestvalidparentheses (self, s):
Start = 0
Max_so_far = 0
stack = []
For i in Xrange (Len (s)):
If s[i] = = "(":
Stack.append (min (i, start))
start = i + 1
Else
If Len (stack) >=1:
Start = last = Stack.pop ()
Max_so_far = Max (i-last+1, Max_so_far)
Else
start = i + 1
Return Max_so_far
def main ():
s = solution ()
Print s.longestvalidparentheses ("() ()")
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]32:longest Valid parentheses