码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Longest Valid Parentheses"

时间:2014-08-06 14:37:41      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   amp   

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

LeetCode "Longest Valid Parentheses",布布扣,bubuko.com

LeetCode "Longest Valid Parentheses"

标签:style   blog   color   io   for   ar   div   amp   

原文地址:http://www.cnblogs.com/tonix/p/3894390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!