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 {
public:
    int longestValidParentheses(string s) {
        int n = s.length();
	    int result = 0;
	    if (n < 2)
	    {
		    return 0;
	    }

	    int buf[n+1];
	    memset(buf, 0, (n+1)*sizeof(int));
	    int count = 0;
	    for (int i = 1; i <= n; i++)
	    {
		    if (s[i-1] == '(')
		    {
			    count++;
		    }
		    else if (count > 0)
		    {
			    count--;
			    buf[i] = 2;
			    if (s[i-2] == ')')
			    {
				    buf[i] += buf[i-1];
			    }
			    buf[i] += buf[i-buf[i]];
			    if (buf[i] > result)
			    {
				    result = buf[i];
			    }
		    }
	    }

	    return result;
    }
};


你可能感兴趣的:(Longest Valid Parentheses)