Skip to content

Instantly share code, notes, and snippets.

@zhangxiaomu01
Created December 9, 2018 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangxiaomu01/1c56193e1c1c8908bbcccf5f0e639568 to your computer and use it in GitHub Desktop.
Save zhangxiaomu01/1c56193e1c1c8908bbcccf5f0e639568 to your computer and use it in GitHub Desktop.
class Solution {
public:
int longestValidParentheses(string s) {
int left = 0, right = 0, maxLen = 0;
int len_s = s.size();
for(int i = 0; i<len_s; i++){
if(s[i] == '(')
left++;
else
right++;
if(left == right) maxLen = max(maxLen, 2*right);
else if(right > left) left = right = 0;
}
left = right = 0;
for(int i = len_s - 1; i>=0 ; i--){
if(s[i] == '(')
left++;
else
right++;
if(left == right) maxLen = max(maxLen, 2*left);
else if(right < left) left = right = 0;
}
return maxLen;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment