C++ Using left and right parentheses count
\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int left=0,right=0,maxlen=0;\n        for(int i=0;i<s.size();i++){\n          
```\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int left=0,right=0,maxlen=0;\n        for(int i=0;i<s.size();i++){\n            if(s[i]==\'(\')\n                left++;\n            if(s[i]==\')\')\n                right++;\n            if(left==right)\n                maxlen=max(maxlen,2*left);\n\t\t//when we traverse from left to right ,if right becomes more than left then we enter into invalid state\n            else if(right>=left){\n                left=0;\n                right=0;\n            }\n        }\n        left=0,right=0;\n        for(int i=s.size()-1;i>=0;i--){\n            if(s[i]==\'(\')\n                left++;\n            if(s[i]==\')\')\n                right++;\n            if(left==right)\n                maxlen=max(maxlen,2*right);\n\t\t//when we traverse from right to left ,if left becomes more than right we enter into inavild state\n            else if(left>=right){\n                left=0;\n                right=0;\n            }\n        }\n        return maxlen;\n        \n        \n    }\n};\n```
[]