Thursday, August 21, 2014

Longest Valid Parentheses

Problem:

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

Idea:
1. Need to push the indices of '('
2. last needs to be initialized as -1 instead of 0 for    lmax = max(lmax,i-last); work

    int longestValidParentheses(string s) {
        vector<int> left;
       int n=s.size();
       int last=-1,lmax=0;
       for (int i=0; i<n; i++)
       {
            if (s[i]=='(')
             {
              left.push_back(i);
              }
              else if (s[i]==')')
              { 
                     if (left.empty())
                     {
                         last=i;
                    }
                    else
                    {
                        left.pop_back();
                        if (left.empty())
                        {
                            lmax = max(lmax,i-last);
                        }
                        else
                        lmax = max(lmax,i-left.back());
                    }
              }
       }
       return lmax;
    }

No comments:

Post a Comment