Created
December 9, 2018 05:14
-
-
Save zhangxiaomu01/694e23f91263a48968d8a44b1aeb713c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int longestValidParentheses(string s) { | |
int len_s = s.size(); | |
int dp[len_s+1]{0}; | |
int maxLen = 0; | |
for(int i = 1; i < len_s; i++){ | |
if(s[i] == ')'){ | |
if(s[i - 1] == '('){ | |
dp[i] = (i-2>=0 ? dp[i - 2] : 0) + 2; | |
} | |
else{ | |
if(i - dp[i-1] - 1 >= 0 && s[i - dp[i-1] - 1] == '(') | |
dp[i] = dp[i-1] + 2 + (i-dp[i-1]-2 >=0 ? dp[i - dp[i-1] - 2] : 0); | |
} | |
} | |
maxLen = max(maxLen, dp[i]); | |
} | |
return maxLen; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment