当前位置:网站首页>32. Longest valid bracket (difficult stack string)
32. Longest valid bracket (difficult stack string)
2022-07-28 22:25:00 【Calm in the wind and rain】
32. Longest valid bracket
Give you one that only contains ‘(’ and ‘)’ String , Find the longest effective ( The format is correct and continuous ) The length of the bracket substring .
Example 1:
Input :s = “(()”
Output :2
explain : The longest valid bracket substring is “()”
Example 2:
Input :s = “)()())”
Output :4
explain : The longest valid bracket substring is “()()”
Example 3:
Input :s = “”
Output :0
Tips :
0 <= s.length <= 3 * 104
s[i] by ‘(’ or ‘)’
source : Power button (LeetCode)
link :https://leetcode.cn/problems/longest-valid-parentheses
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
analysis
Matching questions like parentheses is easy to think of using stacks or dynamic programming , Here, we use the stack and the method of traversing twice in positive and negative order , Dynamic planning can refer to the official solution .
Method 1 : Stack
The idea is to traverse each character of the string , Store all in the stack “(” The subscript , Every encounter “)” Just pop A subscript , At this time, the difference between the subscript at the top of the stack and the subscript currently traversed is the length of the current continuous valid parentheses , It should be noted that the currently continuous valid parentheses are not necessarily the longest , It needs to be compared with the longest length recorded before .
Because we need to use the digital record length at the top of the stack , So the preprocessing stack stores -1.
Method 2 : Two traversal
The optimization space complexity is O(1)
Ideas : First , The left and right parentheses of valid parentheses must be equal ; secondly , Separate right parentheses ( No left parentheses match ) It must not be counted in valid brackets , And if there is such a right parenthesis , Can be used as continuous valid parentheses “ Separator ”.
Then we can consider this , Using two variables left and right Record the number of left and right parentheses respectively , Traversing the string from left to right , Valid parentheses must start with an open parenthesis , End with a right parenthesis , So all valid parentheses begin left Must be greater than right Of , When left = right when , Record the length of the current longest valid bracket ( Use the recorded length and 2 * right comparison ), And then continue to traverse , If you encounter right > left The situation of , Explain the appearance of “ Separator ”, The preceding valid parentheses cannot be continuous with the following , Make left = right = 0, Re recording .
For the above ideas , It can be found that for “(()” This situation starts with multiple left parentheses and ends with fewer right parentheses , Because no left = right appear , So we can't get the valid bracket length , In this case, you can use reverse traversal , First record the number of right parentheses and then the number of left parentheses .
Answer key (Java)
Method 1 :
class Solution {
public int longestValidParentheses(String s) {
int ans = 0;
Deque<Integer> stack = new LinkedList<Integer>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
ans = Math.max(ans, i - stack.peek());
}
}
}
return ans;
}
}
Method 2 :
class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, ans = 0;
for (int i = 0; i < s.length(); i++) {
// positive
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
ans = Math.max(ans, right * 2);
} else if (right > left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
// reverse
if (s.charAt(i) == ')') {
right++;
} else {
left++;
}
if (left == right) {
ans = Math.max(ans, left * 2);
} else if (left > right) {
left = right = 0;
}
}
return ans;
}
}
边栏推荐
- HCIP(14)
- SQL injection less34 (post wide byte injection + Boolean blind injection)
- 笔试总结记录
- SQL注入 Less38(堆叠注入)
- 成立不到一年!MIT衍生量子计算公司完成900万美元融资
- Win11怎么打开软件通知
- How to realize dynamic route switching and route caching in vuejs
- Is mov format a still image file format
- Tensorflow serving high performance machine learning model service system
- Lin Xiaobin, head of Tencent cloud database, borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true
猜你喜欢

【NLP】生成词云

局域网添加DNS服务器进行域名解析

The person in charge of Tencent cloud database borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true

2021 mathematical modeling group B exercise

What is time complexity

阿里云CDN实践

Sword finger offer II 054. Sum of all values greater than or equal to nodes (medium binary search tree DFS)

Chapter 7: drawing rotating cubes

HCIP(11)

Learning notes and summary of C language programming specification
随机推荐
[CS231N]Lecture_ 2:Image Classification pipelin
Data visualization news, different forms of news reports
Brief introduction to PCB materials
小程序 canvas 生成海报
使用百度EasyDL实现明厨亮灶厨师帽识别
ssh 免密码登录
Future trend of defi in bear market
Openresty request authentication
IFLYTEK written examination
Aimbetter insight into your database, DPM and APM solutions
Lin Xiaobin, head of Tencent cloud database, borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true
JMeter installs third-party plug-ins plugins Manager
The applet listens for the target node to appear on the screen
HCIP(12)
Principle of object. Prototype. ToString. Call()
阿里云CDN实践
Why is 0.1 + 0.2 not equal to 0.3? How to solve this problem?
Bugku,Web:都过滤了
Embrace open source guidelines
AimBetter洞察您的数据库,DPM 和 APM 解决方案