Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Yes a typical stack based problem. Please take care of corner cases.

class Solution {
public:
    bool isValidSerialization(string preorder) 
    {        
        //    Get tokens.
        vector<string> tokens; // true - is num; false - is null
        int i = 0; string tk;
        while(i < preorder.length())
        {
            char c = preorder[i];
            if(c == ',')
            {
                tokens.push_back(tk);
                tk.clear();
            }
            else
            {
                tk += c;
            }
            i ++;
        }
        tokens.push_back(tk);
        
        int n = tokens.size();
        if(n==1) return tokens[0] == "#";
        if (n < 3) return false;
        
        //    Go
        typedef pair<string, bool> Rec; // value - is on right
        i = 0;
        stack<Rec> stk;
        if(tokens[0] != "#")
            stk.push(Rec(tokens[i++], false));
        while(!stk.empty() && (i < n))
        {
            string tk = tokens[i++];
            if(tk == "#") // '#'
            {
                if(!stk.top().second) // switch to right
                {
                    stk.top().second = true;
                }
                else
                {
                    while(!stk.empty() && stk.top().second) stk.pop();
                    if(!stk.empty()) stk.top().second = true;
                }
            }
            else 
            {
                stk.push(Rec(tk, false));
            }
        }

        return stk.empty() && (i == n);
    }
};
posted on 2016-02-03 06:08  Tonix  阅读(257)  评论(0编辑  收藏  举报