原网址为https://leetcode.com/problems/longest-valid-parentheses/description/
一、题目
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:
//( -> -1, ) -> -2
int longestValidParentheses(string s) {
vector<int> sta(s.size(), 0);
int top = -1;
map<char, int> m;
m['('] = -1;
m[')'] = -2;
for (int i = 0; i < s.size(); i++) {
if (top != -1 && s[i] == ')' && sta[top] == m['(']) {
sta[top] = sta[top + 1] + 2;
sta[top + 1] = 0;
top = top - 1;
if (top >= 0 && sta[top] > 0) {
sta[top] += sta[top + 1];
sta[top + 1] = 0;
top = top - 1;
}
} else {
if (sta[top + 1] > 0) {
sta[top + 2] = m[s[i]];
top = top + 2;
} else {
sta[top + 1] = m[s[i]];
top = top + 1;
}
}
}
int max = 0;
for (int i = 0; i < sta.size(); i++) {
if (sta[i] > max) max = sta[i];
}
return max;
}
};