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 ans = 0;
int longestValidParentheses(string s) {
bool *a = new bool[s.length()];
memset(a,false,s.length());
stack<int> st;
for(int i = 0;i < s.length();i ++){
if(s[i] == '(')
st.push(i);
else if(s[i] == ')' && !st.empty()){
a[i] = true;
a[st.top()] = true;
st.pop();
}
}
int cur_len = 0;
for(int i = 0;i < s.length();i ++){
if(a[i]) cur_len ++;
else cur_len = 0;
ans = max(ans,cur_len);
}
return ans;
}
};
395

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



