My O(n) solution using a stack
class Solution {\n    public:\n        int longestValidParentheses(string s) {\n            int n = s.length(), longest = 0;\n            stack<int> st;\n      
    class Solution {\n    public:\n        int longestValidParentheses(string s) {\n            int n = s.length(), longest = 0;\n            stack<int> st;\n            for (int i = 0; i < n; i++) {\n                if (s[i] == '(') st.push(i);\n                else {\n                    if (!st.empty()) {\n                        if (s[st.top()] == '(') st.pop();\n                        else st.push(i);\n                    }\n                    else st.push(i);\n                }\n            }\n            if (st.empty()) longest = n;\n            else {\n                int a = n, b = 0;\n                while (!st.empty()) {\n                    b = st.top(); st.pop();\n                    longest = max(longest, a-b-1);\n                    a = b;\n                }\n                longest = max(longest, a);\n            }\n            return longest;\n        }\n    };\n\nThe workflow of the solution is as below.\n\n 1. Scan the string from beginning to end.  \n 2. If current character is '(',\n    push its index to the stack. If current character is ')' and the\n    character at the index of the top of stack is '(', we just find a\n    matching pair so pop from the stack. Otherwise, we push the index of\n    ')' to the stack.\n 3. After the scan is done, the stack will only\n    contain the indices of characters which cannot be matched. Then\n    let's use the opposite side -  substring between adjacent indices\n    should be valid parentheses. \n 4. If the stack is empty, the whole input\n    string is valid. Otherwise, we can scan the stack to get longest\n    valid substring as described in step 3.
[]