Parentheses
check if valid, 須考慮 ')' 在開頭的情況, 遞歸時也要考慮 ’(‘ 個數大於 ’)' 個數
20. Valid Parentheses
678. Valid Parenthesis String
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis
'('
must have a corresponding right parenthesis')'
.Any right parenthesis
')'
must have a corresponding left parenthesis'('
.Left parenthesis
'('
must go before the corresponding right parenthesis')'
.'*'
could be treated as a single right parenthesis')'
or a single left parenthesis'('
or an empty string.An empty string is also valid
22. Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
32. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
dp
State: dp[i], s[:i+1]的LVP
Tran: only consider s[i] == ')', dp[i] = dp[i-2] + 2 if s[i-1] == '(' dp[i] = dp[i-dp[i-1]-1] + 2 if s[i-1] = ')' + dp[i-dp[i-1]-2] if i-dp[i-1]-2 >= 0
List double end traverse
There are only three cases for a string:
'(' are more than ')'
'(' are less than ')'
'(' and ')' are the same
Now, when you scan from left to right, you can only find the correct maxLength
for cases 2 and 3, because if it is case 1, where '(' are more than ')' (e.g., "((()"
), then left
is always greater than right
and maxLength
does not have the chance to be updated.
1190. Reverse Substrings Between Each Pair of Parentheses
You are given a string s
that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Time: O(n^2), Space: O(n)
Time: O(n) for 2 passes, see Lee's explanation
921. Minimum Add to Make Parentheses Valid
Given a string S
of '('
and ')'
parentheses, we add the minimum number of parentheses ( '('
or ')'
, and in any positions ) so that the resulting parentheses string is valid.
1249. Minimum Remove to Make Valid Parentheses
Your task is to remove the minimum number of parentheses ( '('
or ')'
, in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
It is the empty string, contains only lowercase characters, or
It can be written as
AB
(A
concatenated withB
), whereA
andB
are valid strings, orIt can be written as
(A)
, whereA
is a valid string.
301. Remove Invalid Parentheses
example
先計算 需要remove 多少 '(' and ')'
Backtracking, 適當剪支, 符合條件加入答案(利用set, 因為可能重複)
Last updated
Was this helpful?