[leedcode 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) {
        //本题很有难度,要求求出最长匹配的括号长度,遇到括号,首先想到stack数据结构
        //注意栈保存的是下标
        //栈中只存左括号,并维护一个变量max
        //遍历一遍s,若是左括号‘(’则直接push下标
        //若是右括号')',判断此时栈是否为空
        //1)若为空,则用一个变量last记录此时的下标,last初始值是-1
        //2)若栈不为空,表示匹配,弹出栈顶,此时再判断栈是否为空,
        //  i)如果为空,找到了一组匹配字符串max=Math.max(max,i-last);
        // ii)如果不为空,则栈顶的'('还没找到它的')',因为栈顶元素有可能找不到它的')',因此,此时要更新 _max = max(_max, i - stack.peek())
        //对于last的解释,有的博客解释是:当出现右括号,此时栈空时,则当前的')'没有一个'('与它匹配,它可以作用于它左右两个匹配的括号串的分割         //点,用一个变量 last 记录下它的坐标。last的初始值是-1,当遇到新的分割点时,我们更新 last,
        //并可以得到两个 last之间的匹配括号的长度")()()"
        Stack<Integer> stack=new Stack<Integer>();
        int last=-1;
        int max=0;
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='(')
                stack.push(i);
            else{
                if(stack.empty()){
                    last=i;
                    
                }else{
                    stack.pop();
                    if(stack.empty()){
                        max=Math.max(max,i-last);
                        
                    }else{
                        max=Math.max(max,i-stack.peek());
                    }
                    
                    
                }
            }
            
            
            
        }
        return max;
    }
}

 

posted @ 2015-07-09 16:59  ~每天进步一点点~  阅读(92)  评论(0编辑  收藏  举报