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
很明顯是線性時間複雜度。相關文章
- Leetcode Valid ParenthesesLeetCode
- 演算法Valid Parentheses演算法
- Leetcode 20 Valid ParenthesesLeetCode
- Leetcode-Valid ParenthesesLeetCode
- Valid Parentheses leetcode javaLeetCodeJava
- Leetcode 32 Longest Valid ParenthesesLeetCode
- Leetcode-Longest Valid ParenthesesLeetCode
- leetcode 之 Longest Valid ParenthesesLeetCode
- Longest Valid Parentheses leetcode javaLeetCodeJava
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- [LeetCode] Valid Parentheses 驗證括號LeetCode
- LeetCode Valid Parentheses(020)解法總結LeetCode
- [LeetCode] Longest Valid Parentheses 最長有效括號LeetCode
- Leetcode 20 有效的括號valid-parentheses(棧)LeetCode
- LeetCode 之 JavaScript 解答第20題 —— 有效的括號(Valid Parentheses)LeetCodeJavaScript
- 【leetcode】32. Longest Valid Parentheses 最長的有效匹配括號子串長度LeetCode
- Remove Invalid Parentheses[難]REM
- 22. Generate Parentheses (recursion algorithm)Go
- Leetcode 22 Generate ParenthesesLeetCode
- Leetcode-Generate ParenthesesLeetCode
- Generate Parentheses leetcode javaLeetCodeJava
- leetcode22_Generate ParenthesesLeetCode
- 【Python】 Missing parentheses in call to 'print'Python
- LeetCode-Remove Invalid ParenthesesLeetCodeREM
- [LeetCode] Generate Parentheses 生成括號LeetCode
- spring - mvc - @ValidSpringMVC
- Leetcode - 022. Generate ParenthesesLeetCode
- LeetCode-Different Ways to Add ParenthesesLeetCode
- CSS :valid 選擇器CSS
- 941. Valid Mountain ArrayAI
- fatal: Not a valid object name: 'master'ObjectAST
- Leetcode Valid NumberLeetCode
- Leetcode Valid AnagramLeetCode
- Leetcode Valid SudokuLeetCode
- Caused by: Error: ' ' is not a valid resource name characterError
- Please provide a valid cache pathIDE
- Leetcode 36 Valid SudokuLeetCode
- await is only valid in async functionAIFunction