首页 > 代码库 > LeetCode "Longest Valid Parentheses"

LeetCode "Longest Valid Parentheses"

Your intuition would tell you that there‘s a O(n) solution. Actually it is another stack-based problem to solve.

class Solution {public:    struct Rec    {        Rec(char _c, int _inx) : c(_c), inx(_inx) {}        char c;        int inx;    };    int longestValidParentheses(string s) {        int len = s.length();        if (len <= 1) return false;        //    Init        vector<int> rec;        rec.resize(len);        std::fill(rec.begin(), rec.end(), 0);        //    1st pass - mark        stack<Rec> stk;        for (int i = 0; i < len; i++)        {            char c = s[i];            if (c == ()            {                stk.push(Rec((, i));            }            else            {                if (stk.empty()) stk.push(Rec(), i));                else                {                    Rec &top = stk.top();                    if (top.c == ))                    {                        stk.push(Rec(), i));                    }                    else                    {                        rec[top.inx] = i - top.inx + 1;                        for (int i = top.inx + 1; i < top.inx + rec[top.inx]; i++)                        {                            rec[i] == 0;                        }                        stk.pop();                    }                }            }        }//    for        //    2nd - calc        int max = 0;        int j = 0;        while (j < len)        {            int curr = 0;            if (rec[j] > 0)            {                while (rec[j] > 0)                {                    curr += rec[j];                    j += rec[j];                    if (j >= len) break;                }                max = std::max(max, curr);            }            else            {                j ++;            }        }        return max;    }};