Given a containment only'('with')'to find the length of the longest substring containing valid parentheses.
Example 1: Input:"(()"
Output: 2 Explanation: The longest valid parenthetical substring is"()"
Example 2: Input:")()"
Output: 4 Explanation: The longest valid parenthetical substring is"()("
The intuitive way to dynamically program Alibaba Tencent bytes is to calculate the longest valid parentheses starting with i (i from 0 to n - 1ยท) respectively, and take the largest one from them.
*Support: Python
class solution: def longestvalidparentheses(self, s: str) -int: n = len(s) ans = 0 def validcnt(start): cnt is the number of ) minus ( cnt = 0 ans = 0 for i in range(start, n): if s[i] =='(': cnt += 1 if s[i] == ')': cnt -= 1 if cnt < 0: return i - start if cnt == 0: ans = max(ans, i - start + 1) return ans for i in range(n): ans = max(ans, validcnt(i)) return ans
Complexity analysisTime complexity: $o(n 2)$Space complexity: $o(1)$ The main idea is the same as the conventional bracket solution'('Into the stack, encountered')'out of the stack and calculate the length between the two parentheses. Because there are illegal bracket pairs in this question, and the maximum length of the valid bracket pairs is found, there are two points to note:
What is stored in the stack is the subscript of the symbolWhen the stack is empty and the currently scanned symbol is')', you need to put this symbol into the stack as a splitterInitialize a -1 in the stack, asDelimiterLanguage support: python, j**ascript, cppj**ascript code:
Use the stack to solve var longestvalidparentheses = function (s) else }return longest;};
python code:
class solution: def longestvalidparentheses(self, s: str) -int: if not s: return 0 res = 0 stack = [-1] for i in range(len(s)):if s[i] == "(": stack.append(i) else: stack.pop() if not stack: stack.append(i) else: res = max(res, i - stack[-1]) return res
cpp code:
class solution else st.push(i); return ans; }
Complexity analysisTime complexity: $o(n)$Space complexity: $o(n)$We can use the counting method in solution 1.
Iterate once from left to right, and record the number of left and right parentheses left and right, respectively. If right > left, it means that the last point that can be matched cannot be matched to the current point, reset left and right to 0 If right == left, then it can be matched, and the effective parenthesis length is left + right, we get a local optimal solution. If it is larger than the global optimal solution, we update the global optimal solution It is worth noting that the pair is likeIn this way, the logic of updating the global optimal solution can never be executed. One way is to traverse from right to left again, see ** specifically.
Similar ideas have sentinel elements, virtual nodes. However, this method cannot be used in this question.**Support: J**A, Python3, CPP
j**a code:
public class solution else if (left == right) if (right > left) left = right = 0; for (int i = s.length() 1; i >= 0; i--)else if (left == right) if (left > right) return maxlength; }
python3 code:
class solution: def longestvalidparentheses(self, s: str) -int: ans = l = r = 0 for c in s: if c == '(': l += 1 else: r += 1 if l == r: ans = max(ans, l + r) if r > l: l = r = 0 l = r = 0 for c in s[::1]: if c == '(': l += 1 else: r += 1 if l == r: ans = max(ans, l + r) if r < l: l = r = 0 return ans
cpp code:
class solution left = 0, right = 0; for (int i = n - 1; i >= 0; -i) return ans; }
For all dynamic programming problems, the first thing that needs to be solved is how to find the right sub-problem. This problem requires us to find the longest valid pair of parentheses, and the first thing that comes to mind is the definitiondp[i] is the length of the longest valid parenthetical pair for the first i stringsBut then we will find that with such a definition, we can't find any relationship between dp[i] and dp[i-1]. So, we need to find a new definition: definitiondp[i] is the longest valid parenthetical pair length ending with the ith character.Then, let's look at the relationship between dp[i] and dp[i-1] with the following example.
s = '(()'
From the above examples, we can observe the following conclusions (In the description, i is the subscript of the dp array in the graph, the subscript corresponding to s should be i-1, and the i of the ith character starts with 1base case: The longest valid parenthetical pair length of an empty string is definitely 0, i.e.: dp[0] = 0;sThe longest valid parentheses at the end of characters are 0, s of lengthThe length of the longest valid parenthetical pair at the end of the characters is also 0, and we can conclude that the longest valid parenthetical pair cannot be terminated with'('Ending, i.e.: dp[1] = d[2] = 0;When i is equal to 3, we can see dp[2]=0 and dp[3]=2 because the 2nd character (s[1]) and the 3rd character (s[2]) is paired;When i is equal to 4, we can see dp[3]=2 and dp[4]=4 because we are pairing the 1st character (s[0]) and the 4th character (s[3]);Therefore, we can conclude that if the firsticharacters and sectionsi-1-dp[i-1]characters are paired, then dp[i] = dp[i-1] +2, where: i-1-dp[i-1] > = 1, because character 0 has no meaning;According to rule 3, we find dp[5]=0 and dp[6]=2, but obviously, dp[6] should be 6, but we find that it can"(()"with"()"i.e., dp[i] += dp[i-dp[i]], i.e.: dp[6] = 2 + dp[6-2] = 2 + dp[4] = 6 According to the above rules, we solve the dp array as follows: [0, 0, 0, 2, 4, 0, 6, 0], where the length of the longest valid parenthesis pair is 6. The following is **:
*Support: Python3, CPP
python3 code:
class solution: def longestvalidparentheses(self, s: str) -int: mlen = 0 slen = len(s) dp = [0] *slen + 1) for i in range(1, len(s) +1: Valid parentheses are not likely to end with a pair'('If s[i - 1] == at the end'(': continue left_paren = i - 2 - dp[i - 1] if left_paren >= 0 and s[left_paren] == '(': dp[i] = dp[i - 1] +2 concatenate valid parentheses if dp[i - dp[i]]:d p[i] += dp[i - dp[i]] Update the maximum effective expansion length if dp[i] >mlen: mlen = dp[i] return mlen
cpp code:
class solution return ans; }
Complexity analysisTime Complexity: $o(n)$Spatial Complexity: $o(n)$Point 3 feature, The characters that need to be checked are s[i-1] and s[i-2-dp[i-1]], according to the definition: i-1 >= dp[i-1], but i-2 is not necessarily greater than dp[i-1], therefore, it is necessary to check for out-of-bounds;Point 4 feature is the easiest to miss, and there is no need to check for transgressions, because by definition: i >= dp[i], so the boundary case of dp[i-dp[i]] is dp[0];20.valid-parentheses if you judge more than that'('with')', and'[', ']', '', What to do?What if the output is not a length, but a string with any pair of valid parentheses?