iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 30
0
Software Development

刷刷題 or Alan Becker's game 製作 is a question 系列 第 30

(Hard) 32. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

題意: 找出 最長有效子字串

有效:

  • 先左再右
  • 左右形成 one pair
  • 如果以stack法(先進後出)判斷 最後長度為0

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 3 * 104
s[i] is '(', or ')'.


解法:
原本判定 是否有效 以stack 來做的話
符號 '(' or ')'進去判別
但這其實是適用判斷串字串

但這題是求子字串的有效和其字串長度,也就是說: 在有效子字串(s)中看誰最長 --> 動態ansMax更新
而切分點 可由
Ex : ()(() : 2 ( 2 --> 切分點為 '('

Hint : 丟 index 進 stack 可用來計算長度


Code

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack = []
        stack.append(-1)
        ansMax = 0
        if len(s)==0:
            return 0
        for i in range(len(s)):
            if s[i]=='(':
                stack.append(i)
            else:
                stack.pop()
                if len(stack)==0:
                    stack.append(i)
                else:
                    #print(stack[-1])
                    curlen = i - stack[-1]
                    if curlen > ansMax:
                        ansMax = curlen
        print(ansMax)
        return ansMax

上一篇
(Medium) 31. Next Permutation
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言