My easy and simple 12 lines c++ O(N) code using stack


  • 1
    G
    class Solution {
    public:
        int longestValidParentheses(string s) {
            stack<int> st;
            int ans=0;
            st.push(-1);
            for(int i=0;i<s.length();i++)
            {
                if(s[i]=='(') st.push(i);
                else if(st.top()!=-1 && s[st.top()]=='(')
                {
                    st.pop();
                    ans = max(ans,i-st.top());
                }
                else st.push(i);
            }
            return ans;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.