JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

用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 }
复制代码

 

posted on   JasonChang  阅读(227)  评论(0编辑  收藏  举报
编辑推荐:
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
阅读排行:
· AI Agent爆火后,MCP协议为什么如此重要!
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· Java使用多线程处理未知任务数方案
点击右上角即可分享
微信分享提示