题目链接:https://leetcode.com/problems/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.
思路:引入一个栈和一个辅助数组dp[]。
因为左右括号匹配的性质,对于字符串中的字符我们可以做两种操作:
1. 如果是‘(’,则将其位置入栈,代表这个位置有一个需要匹配的左括号。
2. 如果是‘)’,则查找栈:
1)如果此时栈为空,则说明当前段字符串是不合法的。
2)如果此时栈不为空,则说明当前的‘)’可以被匹配。则将从当前‘)’到栈中‘(’位置区间是合法的字符串,则当前合法子串的长度则为
dp[i+1] = (i - j + 1) + dp[j];
即当前匹配的括号的区间长度加上‘(’之前合法子串的长度。
时间复杂度为O(n),空间复杂度为O(n)。
代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
if(s.size() ==0) return 0;
stack<int> st;
vector<int> dp(s.size()+1, 0);
int Max = 0, len=0;
for(int i =1; i <= s.size(); i++)
{
if(s[i-1] == '(') st.push(i);
else if(!st.empty())
{
dp[i] = dp[st.top()-1] + i-st.top()+1;
st.pop();
Max = max(dp[i], Max);
}
}
return Max;
}
};
或者不借助栈, 直接查看和当前右括号匹配的左括号之前的匹配长度和这两个匹配之间的长度.
代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size(), ans = 0;
vector<int> dp(len+1, 0);
for(int i = 2; i <= len; i++)
{
if(s[i-1]=='(') continue;
if(i-dp[i-1]-2 >= 0 && s[i-dp[i-1]-2]=='(')
dp[i] = dp[i-2-dp[i-1]] + dp[i-1]+2;
ans = max(ans, dp[i]);
}
return ans;
}
};
或者不用dp, 只用stack
class Solution {
public:
int longestValidParentheses(string s) {
int len = s.size(), ans = 0;
stack<int> st;
for(int i = 0; i < len; i++)
{
if(s[i]=='(') st.push(i);
else if(!st.empty() && s[st.top()]=='(')
{
st.pop();
ans = max(st.empty()?i+1:i-st.top(), ans);
}
else st.push(i);
}
return ans;
}
};