您的位置:首页 > 编程语言 > Python开发

LeetCode 32. Longest Valid Parentheses

2016-11-07 09:20 330 查看
题目:

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.
题意:
给定一个只含有‘(’‘)’的字符串,找到可以配对的最长子串的长度。

题解:

使用计数器,如果是'(',则计数器加1,如果是')'则减1,

根据计数器是否为0,来判断是否配对,类似栈的操作。

class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
def getLongStr(s):
i = 0
count = 0
cur_str = ''
max_len = 0
start = 0
while i < len(s):
if count == 0 and s[i] == ')': #如果前面已经完成配对,当前出现')'时,记录新的起始下标
cur_str = ''
start = i + 1
if s[i] == '(': #如果出现'(',则count+1
count = count +1
cur_str = cur_str + s[i]
if s[i] == ')' and count > 0: #如果计数器大于0(栈内还有元素)且当前字符串为')'
count = count -1
cur_str =cur_str + s[i]
if count == 0 : #如果完成配对
if max_len < len(cur_str):
max_len = len(cur_str)
start = i + 1
i = i + 1
return max_len, count, start

max_len,count,start = getLongStr(s)
if count > 0: #遍历完s时,栈内还有元素
new_s = s[start:len(s)] #截取最后一段起始时的字符串
new_s = new_s[::-1]
reverse_s = ''
for i in range(len(new_s)): #反转字符串,逆序再来找一次
if new_s[i] == '(':
reverse_s += ')'
else:
reverse_s += '('
temp_len, temp_count, temp_start = getLongStr(reverse_s)
return max(max_len,temp_len)
return max_len

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python leetcode