zoukankan      html  css  js  c++  java
  • LeetCode "Verify Preorder Serialization of a Binary Tree"

    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);
        }
    };
  • 相关阅读:
    作业:ATM
    软件开发目录规范
    re模块
    logging模块
    ConfigParser模块&hashlib模块&subprocess模块
    json模块&pickle模块&shelve模块&xml模块
    时间模块time&datetime
    vue里面render详细写法
    node.js创建服务
    vue退出功能的实现
  • 原文地址:https://www.cnblogs.com/tonix/p/5178896.html
Copyright © 2011-2022 走看看