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.
解法1: DP
用一个array,dp[i]表示的是0 … i子串里lvp。首先如果要valid,那么最后一个字符一定是). 这就是说我们只需要在看到)的时候判断一下当前最长的子串。
那么可以得到如下的推算公式。
如果i字符是(,那么如果i-1是(,则代表有一个valid的子串,dp[i] = dp[i - 2] + 2
如果i字符是),那么先要看i - 1位置的最长子串,然后看这个子串的前一个字符是否是(,如果是那么我们又凑满了一个valid的子串。
dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
|
|
解法2: Stack
|
|