用stack,并记录入栈的括号的位置
1 public class Solution { 2 class Node{ 3 char c; 4 int nub; 5 public Node(char c, int nub){ 6 this.c = c; 7 this.nub = nub; 8 } 9 } 10 11 public int longestValidParentheses(String s) { 12 // IMPORTANT: Please reset any member data you declared, as 13 // the same Solution instance will be reused for each test case. 14 15 char[] mychar = s.toCharArray(); 16 int result = 0; 17 int tmp = 0; 18 Stack<Node> mystack = new Stack<Node>(); 19 mystack.push(new Node(')', -1)); 20 21 for(int i=0; i < mychar.length; ++i) 22 { 23 if(mychar[i] == '(') 24 mystack.push(new Node('(',i)); 25 else 26 { 27 if(mystack.peek().c == '(') 28 { 29 mystack.pop(); 30 result = Math.max(result, i - mystack.peek().nub); 31 } 32 else 33 { 34 mystack.push(new Node(')',i)); 35 } 36 } 37 } 38 return result; 39 } 40 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· AI Agent爆火后,MCP协议为什么如此重要!
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· Java使用多线程处理未知任务数方案