LeetCode 32 括号匹配
[LeetCode 32] Longest Valid Parentheses
题目
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
测试案例
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
思路
-
采用栈数据结构。栈中存放各字符的下标。初始时里面放入-1。
-
从左至右依次遍历每个字符。当前字符为左括号就进栈。当前字符为右括号时,如果栈中存在左括号,则出栈。否则,入栈。
-
每当都元素,记下标为 i ,进栈时,就用 i - stack.peek() - 1 更新 max。
-
遍历结束后,需要用 n - stack.peek() - 1 更新 max。
代码如下
class Solution {
public int longestValidParentheses(String s) {
int max = 0, n = s.length(), temp, index = 0;
if(n == 0){
return 0;
}
int[] stack = new int[n + 1];
stack[index++] = -1;
for(int i = 0; i < n; i++){
if(s.charAt(i) == '(' || (temp = stack[index - 1]) == -1 ||
s.charAt(temp) == ')'){
if((temp = i - stack[index - 1] - 1) > max){
max = temp;
}
stack[index++] = i;
}
else{
index--;
}
}
if((temp = n - stack[index - 1] - 1) > max){
max = temp;
}
return max;
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
· 程序员转型AI:行业分析