Easy to understand and Best solution |beats  100% in time  and space complexity
Intuition\n#### The problem requires us to find the longest valid parentheses substring in a given string of parentheses. A valid substring of parentheses has e
# Intuition\n#### The problem requires us to find the longest valid parentheses substring in a given string of parentheses. A valid substring of parentheses has every opening parenthesis matched with a closing parenthesis in the correct order. Using a stack can help us keep track of unmatched parentheses positions, allowing us to identify the lengths of valid substrings\n\n# Approach\n### Build a stack which contain only index of that parantheses which may causing error while creating valid parantheses :\n\n- Create a stack to keep track of indices of unmatched parentheses.\n- Traverse the string character by character using a loop.\n- If the current character is \'(\', push its index onto the stack.\n- If the current character is \')\':\n- Check if the stack is empty or the character at the index on top of the stack is not \'(\'. If either condition is true, push the current index onto the stack.\n- Otherwise, pop the top index from the stack (indicating a matched pair of parentheses).\n\n### Calculating the length of valid substrings:\n\n- After processing the entire string, use the stack to determine the lengths of the valid substrings.\n- The stack will contain indices of unmatched parentheses.\n- Initialize end to n and substr to 0.\n- Pop an index from the stack and calculate the length of the substring from end to the popped index minus 1.\n- Update end to the popped index.\n- Update substr with the maximum length found so far.\n- Finally, check the interval from the start of the string to the last unmatched index or the end of the string if the stack is empty\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# \uD83E\uDEE1if(you are getting the approach)please try to do upvote++;\n\n# Code\n```\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int n=s.size();\n        stack<int>st;\n        int i=0;\n        while(i<n){\n            if(s[i]==\'(\')st.push(i);\n            else if(s[i]==\')\'){\n                if(st.empty() || s[st.top()]!=\'(\')st.push(i);\n                else if(s[st.top()]==\'(\')st.pop();\n            }\n            i++;\n        }\n        int substr = 0;\n        int end = n; \n        \n        while (!st.empty()) {\n            int l = st.top();\n            st.pop();\n            substr = max(substr, end - l - 1);\n            end = l; \n        }\n        substr = max(substr, end);   \n        \n        return substr;\n    }\n};\n```
['String', 'Stack', 'C++']