Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

 1 class node{
 2     char c= ' ';
 3     int i=0;
 4     public node(char c,int i){
 5         this.i=i;
 6         this.c =c;
 7     }
 8 }
 9 public class Solution {
10     public int longestValidParentheses(String s) {
11         int len = s.length();
12         int max = 0;
13         Stack<node> stack = new Stack<node> ();
14         stack.push(new node(')',-1));
15         for(int i=0;i<len;i++){
16             char c = s.charAt(i);
17             if(c=='('){
18                 stack.push(new node(c,i));
19             }
20             else{
21                 if(stack.peek().c=='('){
22                     stack.pop();
23                     max = Math.max(max,i-stack.peek().i);
24                 }
25                 else{
26                     stack.push(new node(c,i));
27                 }
28             }
29         }
30         return max;
31     }
32 }
View Code

 

posted @ 2014-02-19 00:28  krunning  阅读(149)  评论(0编辑  收藏  举报