longest valid parentheses
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0, start = 0;
stack<int> m;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(') m.push(i);
else if (s[i] == ')') {
if (m.empty()) start = i + 1;
else {
m.pop();
res = m.empty() ? max(res, i - start + 1) : max(res, i - m.top());
}
}
}
return res;
}
};
DP[i] = DP[i-1] + 2 + DP[j]//why DP[j]? 如()()()((..))
REF:
- http://www.cnblogs.com/grandyang/p/4424731.html
- http://bangbingsyb.blogspot.ca/2014/11/leetcode-longest-valid-parentheses.html
- https://leetcodenotes.wordpress.com/2013/10/19/leetcode-longest-valid-parentheses-%E8%BF%99%E7%A7%8D%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%EF%BC%8C%E6%9C%80%E9%95%BF%E7%9A%84valid%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%E6%9C%89%E5%A4%9A/