标签:find ++ release color 思路 solution The 说明 content
? ? ? ? ? ?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.
解题思路:
? ? 这题能够用栈或者dp做,只是自己用栈写的O(N)的解法没有dp的快,所以说下dp的思路吧.
首先,看下状态的定义:
class Solution {
public:
int longestValidParentheses(string s)
{
int n = s.size(), dp[n];
dp[0] = 0;
for (int i = 1; i < n; ++i)
{
int tmp = i - 1 - dp[i - 1];
if (s[i] == ‘(‘)
dp[i] = 0;
else if (tmp >= 0 && s[tmp] == ‘(‘)
dp[i] = dp[i - 1] + 2 + (tmp - 1 >= 0 ? dp[tmp - 1] : 0);
else
dp[i] = 0;
}
return *max_element(dp, dp + n);
}
};
? ? ?
LeetCode:Longest Valid Parentheses
标签:find ++ release color 思路 solution The 说明 content
原文地址:https://www.cnblogs.com/mqxnongmin/p/10659478.html