✅C++ || Easy & Simple || Stack Solution || O(n) || 🗓️ Daily LeetCoding Challenge May, Day 24
Please Upvote If It Helps\n\n\nclass Solution {\npublic:\n    int longestValidParentheses(string s) \n    {\n        // created a stack for storing the open par
**Please Upvote If It Helps**\n\n```\nclass Solution {\npublic:\n    int longestValidParentheses(string s) \n    {\n        // created a stack for storing the open parenthesis \n        stack<int> st;\n        st.push(-1);            // initially push -1 to the stack because if there is ) then we can not pop our stack if it is empty\n        \n        int ans = 0;\n        \n        // iterate over the given string\n        for(int i=0;i<s.length();i++)\n        {\n            // if it is open parenthesis then push that index to the stack\n            if(s[i] == \'(\')\n                st.push(i);\n            \n            // if it is close then pop the stack \n            // and check it is empty or not if it is empty then push current value to it because if there is another ) then we can not pop our stack if it is empty\n            // if it is not empty then find the length between the (current index i and stack top index) and store the max value in ans\n            else\n            {\n                st.pop();\n                \n                if(st.empty())\n                    st.push(i);\n                else\n                    ans = max(ans,i-st.top());\n            }\n        }\n        \n        // returning the answer\n        return ans;\n    }\n};\n```
[]