32. Longest Valid Parentheses

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

 

posted @ 2017-09-23 11:50  Weiyu Wang  阅读(127)  评论(0编辑  收藏  举报