Leetcode:Longest Valid Parentheses

来源:互联网 发布:判断素数的条件c语言 编辑:程序博客网 时间:2024/05/01 21:59

Longest Valid Parentheses

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.

    我们遍历这个字符串,用一个stack来保存未匹配的‘(’的位置,往后遍历如果遇到与之匹配的‘)’,则把之弹出栈,并计算子字符串的长度,其中最大长度子字符串即为所求。这里要考虑多对括号累计的长度。分为两种情况:1.栈为空时的累计长度,此时有效长度为之前的累积长度加上现在的匹配长度。 例如()()(),计算到第3对括号时,有效长度为累积长度4加上现在的匹配长度2,得6。注意:只有栈为空时,才使用中间变量“累积长度”来计算子串的有效长度。 2.栈不为空时的情况,此时的有效长度为最后一个匹配的‘)’的位置,与栈顶未匹配的‘(’的位置之间的距离。请结合代码,方便理解。

public class Solution {    public int longestValidParentheses(String s) {        if (s == null) {            return 0;        }        Stack<Integer> stack = new Stack<Integer>();        int maxLen = 0;        int accumulatedLen = 0;        for(int i = 0; i < s.length(); i++) {            if (s.charAt(i) == '(') {                stack.push(i);            } else {                if (stack.isEmpty()) {                    accumulatedLen = 0;                } else {                    int matchedPos = stack.pop();                    int matchedLen = i - matchedPos + 1;                    if (stack.isEmpty()) {                        accumulatedLen += matchedLen;                        matchedLen = accumulatedLen;                    } else {                        matchedLen = i - stack.peek();                    }                    maxLen = Math.max(maxLen, matchedLen);                }            }        }        return maxLen;   }}


0 0