My O(n) time,O(1)space c++ solution,two-way scanning,13 lines,readable


  • 0
    Z
    int longestValidParentheses(string s) {
        int left1=0,right1=0,left2=0,right2=0,ret=0;
        for(int i=0;i<s.size();i++){
            if(s[i]=='(')left1++;
            else right1++;
            if(right1==left1)ret=max(ret,2*left1);
            else if(right1>left1)right1=left1=0;
            if(s[s.size()-1-i]==')')right2++;
            else left2++;
            if(right2==left2)ret=max(ret,2*right2);
            else if(left2>right2)right2=left2=0;
        }
        return ret;
    }

  • 1

    Thanks for sharing, but it is actually far from readable...


Log in to reply
 

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