My solution without any data structure(no stack)


  • 0
    A



    int longestValidParentheses(string s)
    {
    if(s.size() < 2)
    {
    return 0;
    }
    int i = 0;
    int max = 0;
    int k = 0;
    int count = 0;
    for(auto beg = s.begin(); beg != s.end(); beg++)
    {
    if(*beg == '(')
    {
    i++;
    }
    else
    {
    i--;
    count++;
    if(i == 0)
    {
    k = k + 2 * count;
    count = 0;
    if(max < k)
    {
    max = k;
    }
    }
    if(i < 0)
    {
    count = 0;
    i = 0;
    k = 0;
    }
    }
    }
    i = 0;
    k = 0;
    count = 0;
    for(auto j = s.size() - 1; j != -1; j--)
    {
    if(s[j] == ')')
    {
    i++;
    }
    else
    {
    i--;
    count++;
    if(i == 0)
    {
    k = k + 2 * count;
    count = 0;
    if(max < k)
    {
    max = k;
    }
    }
    if(i < 0)
    {
    count = 0;
    i = 0;
    k = 0;
    }
    }
    }
    return max;
    }


  • 0
    C

    Could you please explain the idea behind the solution? It's really hard to understand this.


Log in to reply
 

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