leetcode的python实现--32. 最长有效括号

    技术2025-12-15  2

    leetcode的python实现–32. 最长有效括号

    题目描述 给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。

    示例 1:

    输入: “(()” 输出: 2 解释: 最长有效括号子串为 “()”

    示例 2:

    输入: “)()())” 输出: 4 解释: 最长有效括号子串为 “()()”

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-valid-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路 转化为在nums数组中,寻找最长的连续的0的长度 使用栈stack,将无法匹配的括号的位置都置1 例如:"(()"的nums为[1,0,0] ")()())"的nums为[1,0,0,0,0,1] "()()()"的nums为[0, 0, 0, 0, 0,0] ())()"的nums为[ 0, 0, 1, 0, 0] ()(()"的nums为[ 0, 0, 1, 0, 0] 最后只需要在数组nums中,寻找最长的连续的0的长度

    python3实现

    class Solution: def longestValidParentheses(self, s: str) -> int: n =len(s) if n <2: return 0 stack = [] nums = [0 for i in range(n)] for i in range(n): if s[i] == '(': stack.append(i)#stack 存入括号(对应的下标 if s[i] == ')': if not stack:#将不能匹配的右括号)对应的数组位置置1 nums[i] = 1 else: stack.pop() while stack:#将不能匹配的左括号( 对应位置置1 nums[stack.pop()] = 1 # 转换思路:在nums数组中,寻找最长的连续的0的长度 res = 0 count = 0 for i in nums: if i == 1: count = 0 continue count += 1 res = max(res, count) return res

    欢迎关注公众号-算法学习总结,获取更多题解,欢迎共同交流学习

    Processed: 0.009, SQL: 9