C++ using Stack
Approach\nIn My solution, trash indicates breakpoint or we can say that when we encounter \')\' but we don\'t have any \'(\' in stack to fulfil it , we can say 
# Approach\nIn My solution, trash indicates breakpoint or we can say that when we encounter \')\' but we don\'t have any \'(\' in stack to fulfil it , we can say next longer parentheses will start after this index and we need to keep track it since we are not inserting this into stack, \nand for rest if stack is not empty we can easily say (index-st.top());\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N) due to stack.\n\n# Code\n```\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int n = s.length();\n        \n        stack<int>st;\n        int trash = 0;\n        int ans = 0;\n        for(int i=1; i<=n; i++){\n            if(s[i-1]==\'(\'){\n                st.push(i);\n            }\n            else{\n                if(st.empty()){\n                    trash= i;\n                    continue;\n                }\n                else{\n                    st.pop();\n                }\n                if(st.empty()){\n                    ans= max(ans, (int)(i-trash));\n                }\n                else{\n                    ans= max(ans, (int)(i-st.top()));\n                } \n            }\n            \n        }\n        return ans;\n    }\n};\n```
['C++']