32. Longest Valid Parentheses
来源:互联网 发布:数据库分析工具 编辑:程序博客网 时间:2024/05/22 13:48
# *- coding:utf-8 -*'''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.时间复杂度:O(n)使用栈来存储'(' 与')'在字符串s中的索引值index,当*s为'('时把该索引值加入栈;否则从栈中pop一个值,d当栈为空时,把')'的索引值加入栈栈初始化时第一个值为-1,因为第j个位置与第i个位置之间有j-i+1个字符'''class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ if s=='': return 0 sSize=len(s) stack=[-1] max_len=0 for i in range(sSize): if s[i]=='(': stack.append(i) else: stack.pop() if stack==[]: stack.append(i) else: max_len=max(max_len,i-stack[-1]) return max_len def longest(self,s): if s=='': return 0 sSize=len(s) stack=[] for i in range(0,sSize): if s[i]=='(': stack.append(i) elif stack!=[] and s[stack[-1]]=='(': stack.pop() else: stack.append(i) max_len=0 rer=sSize pre=0 print stack if stack==[]: return sSize else: while stack!=[]: pre=stack.pop() max_len=max(max_len,rer-pre-1) rer=pre max_len=max(max_len,rer) return max_lenmyp=Solution()s=')((()))))))' # ()(()(print myp.longestValidParentheses(s)
阅读全文
0 0
- 32.Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 堆排序
- 学习笔记-面向对象思想
- TensorFlow基础知识2-张量
- ThinkPHP5 域名单独分组路由
- Class类
- 32. Longest Valid Parentheses
- MySQL中子查询IN,EXISTS,ANY,ALL,SOME,UNION介绍
- $.ajax中contentType: “application/json” 的用法
- 网络搭建
- python爬虫学习第八天
- 【CodeForces
- Java基础 —— 原生数据类型与包装类
- [Visual Studio]MFC游戏开发之回合制对战系统二_by书訢
- Ajax的Result工具类