(LeetCode)Longest Valid Parentheses

动态规划实现:

int longestValidParentheses(string s) {
        if(s.length() <= 1) return 0;
        int curMax = 0;
        vector<int> longest(s.size(),0);
        for(int i=1; i < s.length(); i++){
            if(s[i] == ')' && i-longest[i-1]-1 >= 0 && s[i-longest[i-1]-1] == '('){
                    longest[i] = longest[i-1] + 2 + ((i-longest[i-1]-2 >= 0)?longest[i-longest[i-1]-2]:0);
                    curMax = max(longest[i],curMax);
            }
        }
        return curMax;
    }

用堆栈实现的:

 public int longestValidParentheses(String s) {
       Stack<Integer> stack = new Stack();
        boolean []end = new boolean[s.length()];
        for(int i = 0; i < s.length() ; i ++)
            end[i] = false;

        for(int i = 0 ; i < s.length() ; i ++)
        {
            if(s.charAt(i) == '(')
                stack.push(i);
            else if(!stack.isEmpty())
                end[stack.pop()] = end[i] = true;
        }

        int nowsum = 0,maxsum = 0;
        for(int i = 0 ; i < s.length() ; i ++)
        {
            if(end[i] == false)
                nowsum = 0;
            else{
                nowsum ++;
                if(nowsum > maxsum)
                    maxsum = nowsum;
            }
        }

        return maxsum;
    }
点赞