6/19/2014

131. Longest Valid Parentheses

public class Solution {
    public int longestValidParentheses(String s) {
        if (s.length()<2) return 0;
       
        Stack<Integer> stack = new Stack<Integer> ();
       
        int max = 0;
        int last = -1;
       
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i)=='(') {
                stack.push(i);
            } else {
                if (stack.isEmpty()) {
                    last = i;
                } else {
                    stack.pop();
                    if (stack.isEmpty()) {
                        max = Math.max(max, i-last);
                    } else {
                        max = Math.max(max, i-stack.peek());
                    }
                }
            }
        }
       
        return max;
    }
}

没有评论:

发表评论