Two Approaches Using Stack and without space
Using Stack:\n\nclass Solution:\n    def longestValidParentheses(self, s: str) -> int:\n        stack=[]\n        stack.append(-1)\n        ans=0\n        for i
# Using Stack:\n```\nclass Solution:\n    def longestValidParentheses(self, s: str) -> int:\n        stack=[]\n        stack.append(-1)\n        ans=0\n        for i in range(len(s)):\n            if s[i]==\'(\':\n                stack.append(i)\n            else:\n                stack.pop()\n                if len(stack)==0:\n                    stack.append(i)\n                ans=max(ans,i-stack[-1])\n        return ans\n```\n# without Space complexity:\n```\nclass Solution:\n    def longestValidParentheses(self, s: str) -> int:\n        open,close,ans=0,0,0\n        for i in s:\n            if i=="(":\n                open+=1\n            else:\n                close+=1\n            if close==open:\n                ans=max(ans,close+open)\n            elif close>open:\n                open=close=0\n        open=close=0\n        for i in range(len(s)-1,-1,-1):\n            if "("==s[i]:\n                open+=1\n            else:\n                close+=1\n            if close==open:\n                ans=max(ans,close+open)\n            elif open>close:\n                open=close=0\n        return ans\n```
['Stack', 'Python', 'Python3']