Longest Valid Parentheses

这道题最大的问题是位置容易想不清楚

public class Solution {
    public int longestValidParentheses(String s) {
        // http://blog.csdn.net/linhuanmars/article/details/20439613
        
        if(s ==null || s.length()<2) return 0;
        
        Stack<Integer> st = new Stack<Integer>();
        
        int max =0, start =0;
        
        for(int i = 0; i< s.length(); i++){
            if(s.charAt(i)=='('){
                st.push(i);
            }else{
                if(st.isEmpty()){
                    start = i+1;
                }else{
                    st.pop();
                    max = st.isEmpty()? Math.max(max, i-start+1):Math.max(max, i-st.peek()); // 和当前'('配对的必须是合法的,也就是说(()和最后一个配对的必须是第二个(而不是开头的那个
                }
            }
                
        }
        
        return max;
    }
}

 

posted @ 2015-06-02 04:58  世界到处都是小星星  阅读(118)  评论(0编辑  收藏  举报