Search This Blog

Sunday, December 16, 2012

LeetCode:Longest Valid Parentheses

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.

public class Solution {
    public int longestValidParentheses(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        char[] c = s.toCharArray();
        Stack<Integer> store = new Stack<Integer>();
        int[] right = new int[c.length];
        
        int res=0;
        for(int i=0;i<c.length;i++){
            if(c[i]=='('){
                store.push(i);
            }else{
                if(!store.isEmpty()){
                    right[i]=store.pop()+1;
                    int temp = right[i]-2;
                    if(temp>=0 && right[temp]>0){
                        right[i]=right[temp];    
                    } 
                    res=Math.max(i-right[i]+2,res);
                }
            }
        }
        return res;
    }
}

No comments: