Explaining solution using Stack
I have seen a lot of good answers but it is not immediately clear how they are achieving the result. I am going to make an attempt to explain my solution using 
I have seen a lot of good answers but it is not immediately clear how they are achieving the result. I am going to make an attempt to explain my solution using a stack. Every time we encounter '(' we push the index onto the stack and when we encounter ')' we pop the stack and use the current index minus the index at the top of the stack to be the current_length. we check against the max found so far and update if needed. Here is the code\n\n \n\n    public static int longestValidParentheses(String s) {\n    \n    \n            Stack<Integer> bracketStack = new Stack<Integer>();\n            int max_len=0;\n            int current_len=0;\n            int last = -1;\n            for (int i = 0; i < s.length(); i++) {\n                if (s.charAt(i) == '(') {\n                    \n                        bracketStack.push(i);\n                }\n                else{\n    \n                    if(!bracketStack.isEmpty())\n                    {\n                        bracketStack.pop();\n    \n                    if(!bracketStack.isEmpty())\n                        current_len = i-bracketStack.peek();\n                    else\n                        current_len=i-last;\n                    max_len = Math.max(max_len,current_len);\n                    }\n                    else{\n                        \n                        last = i;\n                    }\n                }\n    \n            }\n    \n    \n            return max_len;\n        }
['Java']