leetcode32_Longest Valid Parentheses

橘子oly發表於2016-10-29

一.問題描述

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4

即給定一個只含有左右括號的字串,輸出其最長有效左右括號的長度。


二.程式碼編寫

    這道題雖然是hard,但是很簡單。首先要清楚怎樣的括號子串是合法的,第一個要滿足的條件是左括號個數一定要小於右括號個數。不過這樣只適合判斷子串是否為合法的。我想的方法是通過出入棧的方式,將匹配的括號彈出棧,那麼最後剩下括號及其在原串中的位置,通過位置之間的最大差來得到最大合法括號子串。程式碼如下:

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack_list = []   # 新建一個括號棧list[即用list實現棧]
        len_s = len(s)
        for i in range(len_s):
            ss = s[i]
            if ss == '(':
                stack_list.append([i,ss])  # 左括號入棧
            else:
                if stack_list != [] and stack_list[-1][1]=='(':
                    stack_list.pop()   # 右括號,若棧頂是左括號則彈出棧
                else:
                    stack_list.append([i,ss]) #右括號,若棧頂為右括號或棧已空,則右括號入棧
        stack_list.append([len_s,0]) 
        maxr = 0
        before = -1
        for sta in stack_list:  # 找到最大括號間隔
            maxr = max(maxr,sta[0]-before-1)
            before = sta[0]
        return maxr
很明顯是線性時間複雜度。

相關文章