Simple Java Solution with O(n)
\n\nclass Solution {\n    // TC : O(n)\n    // SC : O(n)\n    public int longestValidParentheses(String s) {\n        if(s==null || s.length()<2){\n            
\n```\nclass Solution {\n    // TC : O(n)\n    // SC : O(n)\n    public int longestValidParentheses(String s) {\n        if(s==null || s.length()<2){\n            return 0;\n        }\n\n        Stack<Integer> st =new Stack<>();\n\n        for(int i=0;i<s.length();i++){\n            if(s.charAt(i) == \'(\'){\n                st.push(i);\n            } else{\n\n                // current closing bracket\n\n                if(!st.empty() && s.charAt(st.peek()) == \'(\'){\n                    // balanced case\n                    st.pop();\n                } else {\n                    // unbalanced case\n                    st.push(i);\n                }\n            }\n        }\n     \n        int maxLen = 0;\n        int endTerminal = s.length();\n\n        while(!st.empty()){\n            int startTerminal  = st.pop();\n            maxLen = Math.max(maxLen, endTerminal - startTerminal -1);\n            endTerminal = startTerminal;\n        }\n\n        return Math.max(endTerminal, maxLen);\n        \n    }\n}\n```
['Java']