LeetCode 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.

class Solution {
public:
    int longestValidParentheses(string s) {
        /*
        //using stack
        int res = 0, start = 0, n = s.size();
        stack st;
        for(int i = 0; i= 0 ? dp[i-2] : 0) + 2;
                else{
                    if(i - 1 - dp[i-1] >= 0 && s[i - 1 - dp[i-1]] == '(')
                        dp[i] = (i-2-dp[i-1] >= 0 ? dp[i-2-dp[i-1]] : 0) + dp[i-1] + 2;
                }
                maxans = max(maxans, dp[i]);
            }
        }
        return maxans;
    }
};

注意new之后的数组未必初始化为0.
另外还有一种O(1)空间的解法。所有解析见下面的链接。
https://leetcode.com/problems/longest-valid-parentheses/solution/

你可能感兴趣的:(LeetCode Longest Valid Parentheses)