```
class Solution(object):
def longestValidParentheses(self, s):
s_len = len(s)
dp = [0 for i in xrange(s_len)]
stack = 0
m = 0
for i in xrange(s_len):
if s[i] == '(':
stack += 1
else:
if stack > 0:
stack -= 1
dp[i] = dp[i-1] + 1
b = i - 2*dp[i]
if b >= 0:
dp[i] += dp[b]
m = max(dp[i], m)
return m*2
```