1. 程式人生 > >leetcode 32 最長有效括號 O(N)時間解法

leetcode 32 最長有效括號 O(N)時間解法

題目:

給一個只包含 ‘(’ 和 ‘)’ 的字串,找出最長的有效(正確關閉)括號子串的長度。

對於 “(()”,最長有效括號子串為 “()” ,它的長度是 2。

另一個例子 “)()())”,最長有效括號子串為 “()()”,它的長度是 4。

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

思路:
構造一個棧,通過壓棧出棧的方式判斷字串中每個括號的匹配情況。以字元“()(()”為例,這裡匹配出來的結果是 11022也就是說前面兩個是用11表示的是一對匹配的括號,而用22表示的是另一對匹配的括號。這裡,將22換成11並不影響最後對最長的判斷,我們只要在這個新得出的數組裡面找到連續的就行了,能保證有正確的0分割點就可以通過上面的字串計算出最長的長度的 。

程式碼:

class Solution:
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = []
        tmp = [0 for _ in range(len(s))]
        for (i, ch) in enumerate(s):
            if ch == ')':
                if len(stack) == 0:
                    stack.append((ch, i))
                else
: if stack[-1][0] == '(': ele = stack.pop() tmp[ele[1]] = 1 tmp[i] = 1 else: stack.append((ch, i)) else: stack.append((ch, i)) max_counter = 0
counter = 0 for v in tmp: if v == 0: counter = 0 else: counter += 1 if counter > max_counter: max_counter = counter return max_counter s = Solution() print(s.longestValidParentheses('(())')) print(s.longestValidParentheses('()(()'))