标签:dp
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.
int longestValidParentheses(string s) { if (s.empty()) return 0; int max =0; vector<int>Maxlength(s.size(),0); for (int i = Maxlength.size()-2;i>=0;--i) { if (s[i]=='(') { int j = i+1+Maxlength[i+1]; if (j<s.size()&&s[j]==')') { Maxlength[i] = Maxlength[i+1]+2; if (j+1<s.size()) Maxlength[i]+=Maxlength[j+1]; } } max =max<=Maxlength[i]?Maxlength[i]:max; } return max; }
int longestValidParentheses(string s) { if (s.empty()) return 0; stack<int>CharStack; CharStack.push(-1); int length =0; int longestlength =0; for (int i = 0;i!=s.size();++i) { if (s[i]=='(') CharStack.push(i); else if (s[i]==')') { if (CharStack.size()>1) { CharStack.pop(); length=i-CharStack.top(); longestlength =max(longestlength,length); } else{ CharStack.pop(); CharStack.push(i); } } } return longestlength; }
标签:dp
原文地址:http://blog.csdn.net/li_chihang/article/details/44829041