要求:长度
思路:
法一:栈
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int ans = 0;
for (int i = 0,start = 0; i < s.size(); i++)
{
if (s[i] == '(') st.push(i); //左括号入栈
else
{
if (!st.empty()) //有左括号匹配
{
st.pop(); //匹配成功
if (st.empty()) ans = max(ans, i - start + 1);//从start开始
else ans = max(ans, i - st.top()); //i - st.top() + 1 - 1,//从栈顶开始
}
else start = i + 1; //没左括号匹配,更新起点
}
}
return ans;
}
};
法二:动态规划
class Solution {
public:
int longestValidParentheses(string s) {
int maxans = 0, n = s.length();
vector<int> dp(n, 0);
for (int i = 1; i < n; i++) {
if (s[i] == ')') {
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] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
}
maxans = max(maxans, dp[i]);
}
}
return maxans;
}
};
法三:双指针
class Solution {
public:
int longestValidParentheses(string s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = max(maxlength, 2 * right);
} else if (right > left) {
left = right = 0;
}
}
left = right = 0;
for (int i = (int)s.length() - 1; i >= 0; i--) {
if (s[i] == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = max(maxlength, 2 * left);
} else if (left > right) {
left = right = 0;
}
}
return maxlength;
}
};