sourcecode

Tuesday, December 4, 2012

Longest Valid Parentheses


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.
 
class Solution {//medium
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<int> left;//position of '('
        for(int ii = 0; ii < s.size(); ++ii){
            if (s[ii] == '(') left.push(ii);
            else if (!left.empty()){//')'
                s[ii] = 'k';
                s[left.top()] = 'k';
                left.pop();
            }
        }
        int maxLength = 0;
        int length = 0;
        for(int ii = 0; ii < s.size(); ++ii){
            if (s[ii]=='k'){
                ++length;                
                if (maxLength < length) maxLength = length;
            }
            else length = 0;

        }
        return maxLength;
    }
};

No comments: