Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-in Event, click to viewactivity details。
1. Description of the topic
source:LeetCode
Given a string containing only '('
sums ')'
, find the length of the longest valid (well-formed and consecutive) parenthesized substring.
Example 1:
输入:s = "(()"
输出:2
解释:最长有效括号子串是 "()"
复制代码
Example 2:
输入:s = ")()())"
输出:4
解释:最长有效括号子串是 "()()"
复制代码
Example 3:
输入:s = ""
输出:0
复制代码
hint:
- 0 <= s.length <= 3 * 104
- s[i] is '(' or ')'
2. Thought analysis
栈
in the previous【Brush the question record】20. Valid parenthesesWe 栈
implemented the test for valid parentheses using this question on the basis of
-
Traverse the string
s
. Usei
to record the current traversal position, and usej
to record the start position of the nearest longest valid bracket. -
For each encountered
(
, we put its subscript on the stack, -
For each encountered
)
, we pop the top element of the stack to indicate that the current closing parenthesis is matched: -
If the stack is empty, it means that the current closing bracket is an unmatched closing bracket,
j
and the subscript is used to calculate the length. -
If the stack is not empty, use the subscript of the top element of the stack to calculate the length.
3. Code Implementation
class Solution {
public int longestValidParentheses(String s) {
Deque<Integer> stack = new ArrayDeque<>();
int res = 0;
for (int i = 0, j = -1; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.addLast(i);
} else {
if (!stack.isEmpty()) {
stack.pollLast();
int top = j;
if (!stack.isEmpty()) top = stack.peekLast();
res = Math.max(res, i - top);
} else {
j = i;
}
}
}
return res;
}
}
复制代码
Complexity Analysis
- time complexity:
,
n
the length of the string - Space complexity:
,
n
the length of the string
operation result
Summarize
This question is also an enhanced variant of the previous question. The main thing is to use the stack to achieve efficient matching of parentheses.
For different problems, choose the appropriate data structure to solve our problems more quickly.
keep going~~