LeetCode

题目:

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.

思路:

在栈中保存上一个"("的位置

package ds;

import java.util.Stack;

public class LongestValidParentheses {

    public int longestValidParentheses(String s) {
        int len;
        if (s == null || (len = s.length()) < 2) return 0;
        Stack<Integer> stack = new Stack<Integer>();
        int max = 0;
        int lastIndex = -1;
        int i = 0;
        while (i < len) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                if (stack.isEmpty()) {
                    lastIndex = i;
                } else {
                    stack.pop();
                    if (stack.isEmpty()) {
                        max = Math.max(max, i - lastIndex);
                    } else {
                        max = Math.max(max, i - stack.peek());
                    }
                }
            }
            ++i;
        }
        
        return max;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LongestValidParentheses l = new LongestValidParentheses();
        System.out.println(l.longestValidParentheses(""));
    }

}
原文地址:https://www.cnblogs.com/null00/p/5066977.html