题目地址:
https://leetcode.com/problems/longest-valid-parentheses/
描述:
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.
分析
自己最开始的考虑是用stack存储“(”,当遇到“)”则tmp++并pop,ans=max(ans,tmp)。stack为空且当前为“)”时是丢弃的。
但对于“(()(((()”,以上做法是错误的。尝试去补救处理一些出错的情况,但是代码越写越复杂。
参考1:https://segmentfault.com/a/1190000003481194 ,可以将下标压入stack(而不是“(”),计算valid parentheses substring时是减去stack中未能匹配的坐标,即得到已经匹配了的串长。
参考2:http://www.cnblogs.com/easonliu/p/3637429.html ,用一个bool数组来标记已经匹配过的字符,找到最长的连续标记的长度就是所求的结果。
https://leetcode.com/problems/longest-valid-parentheses/
描述:
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.
分析
自己最开始的考虑是用stack存储“(”,当遇到“)”则tmp++并pop,ans=max(ans,tmp)。stack为空且当前为“)”时是丢弃的。
但对于“(()(((()”,以上做法是错误的。尝试去补救处理一些出错的情况,但是代码越写越复杂。
参考1:https://segmentfault.com/a/1190000003481194 ,可以将下标压入stack(而不是“(”),计算valid parentheses substring时是减去stack中未能匹配的坐标,即得到已经匹配了的串长。
参考2:http://www.cnblogs.com/easonliu/p/3637429.html ,用一个bool数组来标记已经匹配过的字符,找到最长的连续标记的长度就是所求的结果。
代码(根据第一个参考)
class Solution {
public:
int longestValidParentheses(string s) {
stack<pair<int,char>> st;
int ans=0;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
st.push(make_pair(i,'('));
}else{
if(!st.empty() && (st.top()).second=='('){
st.pop();
ans=max(ans,st.empty() ? i+1 : i-(st.top()).first);
}else
st.push(make_pair(i,')'));
}
}
return ans;
}
};