parentheses - 32. Longest Valid Parentheses

7
  1. Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

思路:

括号问题常规解法都是使用栈。

代码:

java:

class Solution {

    public int longestValidParentheses(String s) {

        Stack<Integer> stack = new Stack<>();
        int res = 0, left = -1;  // 等于-1是为了避免第一位就是左括号的情况
        
        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()) {
                        res = Math.max(res, i - left);
                    } else {
                        res = Math.max(res, i - stack.peek());
                    }
                }
            }
        }
        
        return res;
    }
}