首页 > 代码库 > Longest Valid Parentheses @Leetcode -- Python
Longest Valid Parentheses @Leetcode -- Python
http://oj.leetcode.com/problems/longest-valid-parentheses/
1 class Solution: 2 # @param s, a string 3 # @return an integer 4 def longestValidParentheses(self, s): 5 if s == ‘‘ or s == ‘(‘ or s == ‘)‘: 6 return 0 7 stack = [(-1, ‘)‘)] 8 maxLen = 0 9 for i in xrange(len(s)): 10 if s[i] == ‘)‘ and stack[-1][1] == ‘(‘: 11 stack.pop() 12 maxLen = max(maxLen, i - stack[-1][0]) 13 else: 14 stack.append((i, s[i])) 15 return maxLen 16 # test 17 s = Solution() 18 print s.longestValidParentheses("()(()") 19 print s.longestValidParentheses(‘(()()‘) 20 print s.longestValidParentheses(‘)()())‘)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。