Monday, February 17, 2014

Leetcode: 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.

Solution:

public class Solution {
    public int longestValidParentheses(String s) {
        ArrayDeque<Integer> positions = new ArrayDeque<Integer>();
        int lastError = -1;
        int longestChain = 0;
        for(int i=0; i<s.length(); i++)
        {
            if(s.charAt(i)=='(')
                positions.push(i);
            else
            {
                if(positions.isEmpty())
                    lastError = i;
                else
                {
                    positions.pop();
                    int previousValue = positions.isEmpty() ? lastError : positions.peek();
                    longestChain = longestChain < i-previousValue ? i-previousValue : longestChain;
                }
            }
        }
        return longestChain;
    }
}

No comments :

Post a Comment