Wednesday, January 7, 2015

LeetCode 32: 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) {
        // 1. If encounter '(', push its index into stack;
        // 2. If encounter ')' && stack is empty or top is also ')', push its index into stack (This ')' will never be paired).
        // 3. If encounter ')' && the top of stack is '(', pop '(' (Both are paired);
        // 3.a. If then stack is empty, it indicates all of the previous parentheses are paird, len = current index (0-indexed) + 1.
        // 3.b. If then stack isn't empty, len = current index - unpaired parentheses index (top of stack), get max len vs. before.
        int n = s.length();
        int len = 0;
        Stack<Integer> stack = new Stack<>(); // Used to store the indexes of parentheses
        
        for (int i = 0; i < n; i++)
        {
            // Condition 3
            if (s.charAt(i)==')' && !stack.isEmpty() && s.charAt(stack.peek()) == '(')
            {
                stack.pop();
                
                // Condition 3.a
                if (stack.isEmpty())
                    len = i + 1;
                // Condition 3.b
                else
                    len = Math.max(len, i - stack.peek());
            }
            // Condition 1 & 2
            else
                stack.push(i);
        }
        
        return len;
    }
}

No comments:

Post a Comment