iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 33

[Day 33] Longest Valid Parentheses (Hard)

  • 分享至 

  • xImage
  •  

32. Longest Valid Parentheses

Solution 1: Stack

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        ans = 0
        stack = []
        startIdxOfLastValidPair = 0
        for idx in range(len(s)):
            if s[idx] == '(':
                stack.append(idx)
            # s[idx] == ')' and Stack empty
            elif not stack:
                startIdxOfLastValidPair = idx + 1 # e.g, ')()'
            # s[idx] == ')' and Stack has idx of previous '('
            else:
                stack.pop()

                # e.g, '...()()()()...', continuously update ans
                if not stack:
                    ans = max(ans, idx - startIdxOfLastValidPair + 1)
                # e.g, '...(()()...'
                else:
                    ans = max(ans, idx - stack[-1])
        return ans

Time Complexity: O(N)
Space Complexity: O(N)

Solution 2: DP

Time Complexity: O(N)
Space Complexity: O(N)

Solution 3: Two Pointer

Time Complexity: O(N)
Space Complexity: O(1)

Reference

https://www.cnblogs.com/grandyang/p/4424731.html

Follow-up: Valid Parentheses


上一篇
[Day 32] Coin Change (Medium)
下一篇
[Day 34] Find the Duplicate Number (Medium)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言