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);
        }
    };
  • 相关阅读:
    MySQL查看视图
    MySQL创建视图(CREATE VIEW)
    Mysql视图
    Snipaste使用教程
    Mysql全文检索
    MySQL中MyISAM和InnoDB
    MySQL卸载注意事项
    MySql免安装配置(Windows)
    验证用户名密码:Servlet+Maven+Mysql+jdbc+Jsp
    使用response下载文件
  • 原文地址:https://www.cnblogs.com/tonix/p/5178896.html
Copyright © 2011-2022 走看看