数据结构算法操作试题(C++/Python)——最长有效括号

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——最长有效括号,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

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

2. 解答

python:56ms, 12.7MB, 50%

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stackList = []
        for i in range(len(s)):
            if s[i] == "(": stackList.append((s[i], i))
            else:
                if stackList and stackList[-1][0] == "(": stackList.pop()
                else: stackList.append((s[i], i))
                    
        len_ = len(s)
        if not stackList: return len_
        maxCnt = stackList[0][1] - 0
        for i in range(1, len(stackList)):
            maxCnt = max(stackList[i][1] - stackList[i - 1][1] - 1, maxCnt)
        maxCnt = max(len_ - 1 - stackList[-1][1], maxCnt)
        return maxCnt

其他方法看 leetcode 链接 评论区~