有一说一,我觉得这题没有到困难级
要保存之前的状态,感觉是很明显的dp
思路和题解一样
class Solution { public: int longestValidParentheses(string s) { int len=s.length(); int ret = 0; int *dp=new int[len]; for(int i=0;i<len;i++) dp[i]=0; for (int i = 1; i < s.length(); i++) { if (s[i] == ')') { if (s[i - 1] == '(') { dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2; } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { dp[i] = dp[i - 1] + ((i - dp[i - 1]-2) >= 0 ? dp[i - dp[i - 1] - 2] : 0) + 2; } ret=max(ret,dp[i]); } } return ret; } };
然后看了题解,因为只有( H和),只需要用left,right记录即可
扫描两遍的原因是 (() 避免这种情况
class Solution { public: int longestValidParentheses(string s) { int res = 0; int left = 0; int mark = 0; for (int i = 0; i < s.size(); ++i) { int prev_mark = mark; mark = max(0, mark + ((s[i] == '(') ? 1 : -1)); if (mark == 0) { if (prev_mark > 0) { res = max(i - left + 1, res); } else { left = i + 1; } } } mark = 0; int right = s.size() - 1; for (int i = s.size() - 1; i >= 0; --i) { int prev_mark = mark; mark = max(0, mark + ((s[i] == ')') ? 1 : -1)); if (mark == 0) { if (prev_mark > 0) { res = max(right - i + 1, res); } else { right = i - 1; } } } return res; } };