1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
longest-valid-parentheses.py 1.24 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . update
# Time: O(n)
# Space: O(1)
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
def length(it, start, c):
depth, longest = 0, 0
for i in it:
if s[i] == c:
depth += 1
else:
depth -= 1
if depth < 0:
start, depth = i, 0
elif depth == 0:
longest = max(longest, abs(i - start))
return longest
return max(length(xrange(len(s)), -1, '('), \
length(reversed(xrange(len(s))), len(s), ')'))
# Time: O(n)
# Space: O(n)
class Solution2(object):
# @param s, a string
# @return an integer
def longestValidParentheses(self, s):
longest, last, indices = 0, -1, []
for i in xrange(len(s)):
if s[i] == '(':
indices.append(i)
elif not indices:
last = i
else:
indices.pop()
if not indices:
longest = max(longest, i - last)
else:
longest = max(longest, i - indices[-1])
return longest
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助