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.
采用辅助数组length,length[i]表示以i结尾最长的合法字符串的长度。
那么对于一对括号( ),假设(在第j位,)在第k位,如果它们能匹配,则length[k] = length[j - 1] + (k - j + 1)。
用一个堆栈来模拟括号匹配。
class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int ans = 0;
stack<int> stacks;
int length[s.size()];
memset(length, 0, sizeof(int) * s.size());
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
stacks.push(i);
}
else if (s[i] == ')') {
if (!stacks.empty()) {
int idx = stacks.top();
length[i] = i - idx + 1 + (idx > 0 ? length[idx - 1] : 0);
if (length[i] > ans) {
ans = length[i];
}
stacks.pop();
}
}
}
return ans;
}
};
本文介绍了一种使用辅助数组和栈解决最长有效括号子串问题的方法。通过遍历字符串,利用栈来记录左括号的位置,并计算以每个右括号结尾的最长有效括号子串的长度。
395

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



