My Straight Forward Trie based C++ Solution


  • 0
    M
    class Node {
    public:
        string name;
        string content;
        bool isFile;
        map<string, Node*> next;
        Node(string label): name(label), content(""), isFile(false) {}
    };
    
    class FileSystem {
    public:
        FileSystem() {
            root = new Node("/");
        }
    
        /* Get the target node and get all of its children */
        vector<string> ls(string path) {
            vector<string> res;        
            Node* t = find(path);
            if (t->isFile) {
                res.push_back(t->name);
            } else {
                for (auto entry : t->next) {
                    res.push_back(entry.first);
                }
            }
            return res;
        }
        
        /* Add the node */
        void mkdir(string path) {
            addPath(path);
        }
        
        /* Add the node and save the content*/
        void addContentToFile(string filePath, string content) {
            Node* t = addPath(filePath);
            t->content += content;
            t->isFile = true;
        }
    
        /*1. Find the target node. 2. Get the content*/
        string readContentFromFile(string filePath) {
            Node* t = find(filePath);
            return t->content;
        }
        
    private:
        /** Find the node according to given path */
        Node* find(string& path) {
            istringstream in(path.substr(1));
            string token;
            Node* t = root;
            
            while (getline(in, token, '/')) {
                t = t->next[token];
            }
            return t;
        }
        
        /** Add node according to given path */
        Node* addPath(string& path) {
            istringstream in(path.substr(1));
            string token;
            Node* t = root;
            
            while (getline(in, token, '/')) {
                if (!t->next[token]) {
                    t->next[token] = new Node(token);
                }
                t = t->next[token];
            }
            return t;
        }
        
        Node* root;
    };
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.