Using Counter(plus-minus)
Intuition\nInstead of a stack use a simple counter because you dont need to store all nodes information.\n# Approach\nWe can solve this problem using a two-pass
# Intuition\nInstead of a stack use a simple counter because you dont need to store all nodes information.\n# Approach\nWe can solve this problem using a two-pass approach.\n\nFirst, we traverse the string from left to right and count the number of open parentheses \'(\' and the number of closed parentheses \')\'.\n\nWhenever we encounter a closing parenthesis, we decrease the count of open parentheses. If the count becomes negative, it means we\'ve encountered an invalid substring, so we reset our starting index to the current index + 1.\n\nWhenever the count becomes zero, it means we have found a valid substring. We calculate its length and update our maximum length if necessary.\n\nThen, we perform a similar process in the reverse direction, but this time we count the number of open parentheses from right to left.\n\nBy performing these two passes, we can handle cases where the parentheses are not balanced or nested.\n\n\n# Complexity\n- Time complexity:\n0(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n    public static int longestValidParentheses(String s) \n    {\n        int t = s.length();\n        int st = 0;\n        int count = 0,max = 0;\n        for(int i = 0;i<t;i++)\n        {\n            if(s.charAt(i)==\')\')\n                if(count>0)\n                    count--;\n                else\n                {\n                    st = i+1;\n                    count = 0;\n                }\n            else\n                count++;\n            if(count==0)\n                max = Math.max(max,i-st+1);\n        }\n        count = 0;\n        st=t-1;\n        for(int i = t-1;i>=0;i--)\n        {\n            if(s.charAt(i)==\'(\')\n                if(count>0)\n                    count--;\n                else\n                {\n                    st = i-1;\n                    count = 0;\n                }\n            else\n                count++;\n            if(count==0&&st>-1)\n                max = Math.max(max,st-i+1);\n        }\n        return max;\n    }\n}\n```
['Counting', 'Java']