文章 224
评论 6
浏览 200766
parentheses - 32. Longest Valid Parentheses

parentheses - 32. Longest Valid Parentheses

  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;
    }
}


标题:parentheses - 32. Longest Valid Parentheses
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/22/1563805812081.html

Nothing just happens, it's all part of a plan.

取消