leetcode32_Longest Valid Parentheses
一.問題描述
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
很明顯是線性時間複雜度。相關文章
- Longest Valid Parentheses
- Leetcode 20 Valid ParenthesesLeetCode
- Leetcode 32 Longest Valid ParenthesesLeetCode
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- LeetCode Valid Parentheses(020)解法總結LeetCode
- Leetcode 20 有效的括號valid-parentheses(棧)LeetCode
- LeetCode 之 JavaScript 解答第20題 —— 有效的括號(Valid Parentheses)LeetCodeJavaScript
- 【leetcode】32. Longest Valid Parentheses 最長的有效匹配括號子串長度LeetCode
- Leetcode 22 Generate ParenthesesLeetCode
- Leetcode - 022. Generate ParenthesesLeetCode
- 22. Generate Parentheses (recursion algorithm)Go
- LeetCode Generate Parentheses(022)解法總結LeetCode
- 036 Valid Sudoku
- spring - mvc - @ValidSpringMVC
- Leetcode 36 Valid SudokuLeetCode
- 125. Valid Palindrome
- 65-Valid Number
- CSS :valid 選擇器CSS
- fatal: Not a valid object name: 'master'ObjectAST
- Please provide a valid cache pathIDE
- InnoDB: No valid checkpoint found.
- gipchaLowerProcessNode: no valid interfaces found to node
- 941. Valid Mountain ArrayAI
- await is only valid in async functionAIFunction
- Leetcode 611 javascript Valid Triangle NumberLeetCodeJavaScript
- [LeetCode] 678. Valid Parenthesis StringLeetCode
- Caused by: Error: ' ' is not a valid resource name characterError
- A valid provisioning profile for this executable was not found.
- @Valid和@Validated的區別
- @Valid 與 @Validated 的區別
- leetcode 593. Valid Square練習LeetCode
- leetcode 593. Valid Square 練習LeetCode
- Java中@Valid子物件註釋Java物件
- openssl_private_encrypt(): key param is not a valid
- 【leetcode】22. Generate Parentheses 合法括號串的所有組合LeetCode
- Docker 警告 Plugin XXX is not valid: failed to fetch metadataDockerPluginAI
- SSL - SSLHandshakeException: unable to find valid certification path to requested targetException
- @Validated、@Valid在service層引數校驗
- 報錯“Please indicate a valid Swagger or OpenAPI version field”SwaggerAPI