Simple JAVA solution, O(n) time, one stack
\npublic class Solution {\n    public int longestValidParentheses(String s) {\n        Stack<Integer> stack = new Stack<Integer>();\n        int max=0;\n       
```\npublic class Solution {\n    public int longestValidParentheses(String s) {\n        Stack<Integer> stack = new Stack<Integer>();\n        int max=0;\n        int left = -1;\n        for(int j=0;j<s.length();j++){\n            if(s.charAt(j)=='(') stack.push(j);            \n            else {\n                if (stack.isEmpty()) left=j;\n                else{\n                    stack.pop();\n                    if(stack.isEmpty()) max=Math.max(max,j-left);\n                    else max=Math.max(max,j-stack.peek());\n                }\n            }\n        }\n        return max;\n    }\n}\n```
['Java']