Simplest & Shortest | C++
\nclass Solution {\npublic:\n    int longestValidParentheses(string str) {\n        stack<int> s;\n        s.push(-1);\n        int ans = 0, n = str.size();\n  
```\nclass Solution {\npublic:\n    int longestValidParentheses(string str) {\n        stack<int> s;\n        s.push(-1);\n        int ans = 0, n = str.size();\n        for(int i=0; i<n; i++) {\n            if(s.top() != -1 && str[s.top()] == \'(\' && str[i] == \')\') s.pop(), ans = max(ans, i - s.top());\n            else s.push(i);\n        }\n        return ans;\n    }\n};\n```
['Stack', 'C++']