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 2013-11-05 03:37  JasonChang  阅读(223)  评论(0编辑  收藏  举报