[Leetcode] [Python]32:longest Valid parentheses

Source: Internet
Author: User

#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.