2020-07-04-每日一题

更多python分类刷题题解代码:请参考github,博客, 知乎

32. 最长有效括号

https://leetcode-cn.com/problems/longest-valid-parentheses/

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        '''直接暴力找出所有字串,然后判断是否有效(超时)
        '''
        def valid(s):
            '''判断字串是否是有效字串,并返回长度,如果不是就返回0
            '''
            if not s: return 0
            stack = []
            for char in s:
                if char == '(':
                    stack.append(char)
                if char == ')':
                    if not stack: return 0
                    else:
                        stack.pop()
            return len(s) if not stack else 0
            
        if not s: return 0
        max_length = 0
        for i in range(len(s)-1):
            if s[i] == ')': continue 
            for j in range(i+1, len(s)):
                max_length = max(max_length, valid(s[i:j+1]))
        return max_length
class Solution:
    def longestValidParentheses(self, s: str) -> int:
        '''用栈进行括号的匹配
        1、栈从前往后遍历,栈中存储符号与当前索引值
        2、遇到左括号入栈
        3、当遇到右括号时,如果栈顶元素为')',继续入栈,因为没有符号能与当前的右括号相匹配
                        如果栈顶元素为'(',弹出栈顶,此时此字符串的长度为此右括号的索引减去栈顶元素的索引
        '''
        if not s: return 0
        max_length = 0
        stack = []
        for i in range(len(s)):
            if not stack or s[i] == '(':
                stack.append((s[i], i))
            elif s[i] == ')':
                if stack:
                    if stack[-1][0] == ')':
                        stack.append((s[i], i))
                    else:
                        stack.pop()
                        max_length = max(max_length, i - (stack[-1][1] if stack else -1))

        return max_length

更多python分类刷题题解代码:请参考github,博客, 知乎

更多技术文章请点击查看

你可能感兴趣的:(leetcode刷题)