原题:
解决方法:
代码:
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的方法来解,也可以使用DP的方法来解。
当使用stack,首先将-1压栈,然后遇到‘(’入栈;遇到')'出栈,然后计算当前的有效长度,如果stack为空,表明')'有多余的,将当前位置压栈做为后面字符的有效起始位置。
当使用DP时,比较难的是得到推导公式。当是'(',不需要计算。当是')'时,首先判断前一个字符是不是'(',如果是,很容易知道有效长度就是dp[i-2] + 2; 当前一个也是')'时,有效的字符串可以分成三部分:有效字符串 +'(' + 前一个')'组成的有效字符串 + ')',从而推导公式是dp[i] = dp[i-dp[i-1] -2] + 1 + dp[i-1] + 1。
代码:
int longestValidParentheses(string s) {
int n = s.size(), res = 0;
vector<int> dp(n, 0);
for(int i = 1; i < n; i++){
if (s[i] == '(')
continue;
if (s[i-1] == '('){
dp[i] = ((i >= 2) ? dp[i-2] : 0) + 2;
}else if ( (i-dp[i-1]) > 0 && s[i-dp[i-1] - 1]=='(' ){
dp[i] = dp[i-1] + dp[i-dp[i-1] - 2] + 2;
}
res = max(res, dp[i]);
}
return res;
}
int longestValidParentheses1(string s) {
stack<int> st;
st.push(-1);
int res = 0;
for(int i = 0; i < s.size(); i++){
if (s[i] == '('){
st.push(i);
}else{
st.pop();
if (st.empty()){
st.push(i);
}else{
res = max(res, i - st.top());
}
}
}
return res;
}