Longest Valid Parentheses

来源:互联网 发布:国产psp4000淘宝 编辑:程序博客网 时间:2024/06/01 22:40

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;    }};


0 0