Simple easy Java solution O(n) with comments
```\nclass Solution {\n    public int longestValidParentheses(String s) {\n        // create an array to mark valid parenthesis.\n        int[] arr = new int[s.
```\nclass Solution {\n    public int longestValidParentheses(String s) {\n        // create an array to mark valid parenthesis.\n        int[] arr = new int[s.length()];\n        \n        // use a stack to store location of opening brackets.\n        Stack<Integer> stack = new Stack<>();\n        for(int k=0; k<s.length(); k++) {\n            // if opening bracket is found, push its location onto the stack.\n            if (s.charAt(k) == \'(\') {\n                stack.add(k);\n            }\n            // if closing bracket is found and stack is not empty, that means the \n            // the current closing bracket is a pair of the opening bracket at location\n            // available at stack.peek().\n            // mark both location as valid in the array.\n            else if (s.charAt(k) == \')\') {\n                if (!stack.isEmpty()) {\n                    int top = stack.pop();\n                    arr[top] = 1;\n                    arr[k] = 1;\n                }\n            }\n        }\n        // find maximum of continuous valid locations in the array.\n        int max = 0;\n        int curr = 0;\n        for(int k=0; k<arr.length; k++) {\n            if(arr[k] == 1) {\n                curr++;\n            }\n            else {\n                max = Math.max(curr, max);\n                curr = 0;\n            }\n        }\n        return Math.max(curr, max);\n    }\n}
['Stack', 'Java']