当前位置:网站首页>每日一题-最长有效括号-0724
每日一题-最长有效括号-0724
2022-08-05 05:17:00 【菜鸡程序媛】
题目
给你一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
思路
- 括号匹配题目优先从栈的角度切入,本题中需要找到最长的括号子串的长度,通过数组的下标进行匹配
- 优先入栈一个-1的下标,作为栈底的元素(保证栈不会空)
- 遇到左括号的时候入栈,右括号的时候先弹出当前的栈顶元素,如果这个时候栈非空,证明之前入栈过左括号,满足括号对的前提要求;如果是空的,右括号的下标入栈,保证栈不会是空的,还有一点就是后面有满足要求的括号对的时候,作为栈顶下标元素计算当前子串的长度
- 最后通过sum不断迭代,更新当前的最大值
代码
class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length() <= 0)
return 0;
Stack<Integer> stack = new Stack<>();
int sum = 0;
//站岗
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{
sum = Math.max(sum, i - stack.peek());
}
}
}
return sum;
}
}
边栏推荐
猜你喜欢
随机推荐
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)
LeetCode刷题之第55题
电子产品量产工具(2)- 输入系统实现
C语言查看大小端(纯代码)
网管日记:故障网络交换机快速替换方法
LeetCode刷题之第701题
【ts】typescript高阶:映射类型与keyof
八、响应处理——ReturnValueHandler匹配返回值处理器并处理返回值原理解析
【nodejs】第一章:nodejs架构
亲身实感十多年的面试官面试的题目
[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)
常见的 PoE 错误和解决方案
【shell编程】第二章:条件测试语句
OSPF网络类型
SQL (2) - join window function view
LeetCode刷题之第74题
CH32V307 LwIP移植使用
(oj)原地移除数组中所有的元素val、删除排序数组中的重复项、合并两个有序数组
多边形等分
CVPR最佳论文得主清华黄高团队提出首篇动态网络综述
![[Database and SQL study notes] 8. Views in SQL](/img/22/82f91388f06ef4f9986bf1e90800f7.png)








