32. Longest Valid Parentheses

来源:互联网 发布:nginx怎么使用 编辑:程序博客网 时间:2024/05/19 14:54

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.

查找字符串s子串中合法的最长括号长度。

这种最长、最短字符串的处理,一般都可以采用滑动窗口的方法实现,程序如下:

class Solution {    public int longestValidParentheses(String s) {        int len = s.length();        ArrayDeque<Integer> stack = new ArrayDeque<>();        int cnt = 0, length = 0, left = -1;        for (int i = 0; i < len; ++ i){            if (s.charAt(i) == '('){                stack.push(i);                continue;            }            if (stack.isEmpty()){                left = i;            }            else {                stack.pop();                if (stack.isEmpty()){                    length = Math.max(length, i - left);                }                else {                    length = Math.max(length, i - stack.peek());                }            }        }        return length;    }}