/************************************************************************
*
* 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.
*
*
************************************************************************/
用栈去解:压入栈的是索引,这样便于计算长度
如果此时的元素为
(
直接压入栈,因为前面的元素没有和他能配对的。如果此时元素为
)
,分两种情况:
a. 栈为空,则直接将其压入栈中。
b. 栈不空,看栈顶元素是否是(
,若是,将其弹出,因为他们能组成一对,若不是,则将其压入栈中。
我们在第二步符合弹出元素是,计算此时的最大长度maxLen=max(maxLen,i-(st.empty()? -1:st.top()));
其中,分为栈为空和不空的两种情况:
综上所述,代码如下:
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(),maxLen=0;
if (n<2) return 0;
stack<int> st;
for (int i=0;i<n;i++) {
if (s[i]=='(') st.push(i);
else {
if (st.empty()) st.push(i);
else {
if (s[st.top()]=='(') {
st.pop();
maxLen=max(maxLen,i-(st.empty()? -1:st.top()));
}
else st.push(i);
}
}
}
return maxLen;
}
};