题目:
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
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> f(s.size(), 0);
stack<int> t;
int ans = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
t.push(i);
else if (!t.empty()) {
int k = t.top();
t.pop();
f[i] = i - k + 1 + (k > 0 ? f[k - 1] : 0);
ans = max(ans, f[i]);
}
}
return ans;
}
};
本文介绍了一种解决最长有效括号子串问题的方法。利用栈和动态规划思想,找到给定字符串中最大长度的有效括号子串。通过示例说明了如何实现这一算法。
395

被折叠的 条评论
为什么被折叠?



