[588. Design In-Memory File System] C++: Tree structure


  • 0

    Tree structure, unordered_map.

    class tnode{
    public:
    tnode(string s = ""):path_val(s){}
    unordered_map<string, tnode*> children;//its children
    string path_val;//itself's value.
    string ct_val;//content string
    bool isFile = false;
    };
    
    class FileSystem {
    public:
    FileSystem() {
        root = new tnode();
    }
    
    vector<string> ls(string path) {
        if(path.size() == 0) return {};
        vector<string> res;
        int i = 1;
        tnode* rt = root;
        while(i < path.size()){
            string tmp = "";
            while(i < path.size() && path[i] != '/'){
                tmp += path[i++];
            }
            rt = rt->children[tmp];
            i++;
        }
        if(!rt->isFile) {
            for(auto m : rt->children){res.push_back(m.first);}
            sort(res.begin(), res.end());
        }
        else{
            res.push_back(rt->path_val);
        }
        return res;
    }
    
    void mkdir(string path) {
        tnode* rt = root;
        int i = 1;
        while(i < path.size()){
            string tmp = "";
            while(i < path.size() && path[i] != '/'){
                tmp += path[i++];
            }
            if(rt->children.find(tmp) == rt->children.end()){
                tnode* node = new tnode(tmp);
                rt->children[tmp] = node;
            }
            rt = rt->children[tmp];
            i++;
        }
    }
    
    void addContentToFile(string filePath, string content) {
        tnode* rt = root;
        int i = 1;
        while(i < filePath.size()){
            string tmp = "";
            while(i < filePath.size() && filePath[i] != '/'){
                tmp += filePath[i++];
            }
            if(rt->children.find(tmp) == rt->children.end()){
                tnode* node = new tnode(tmp);
                rt->children[tmp] = node;
            }
            rt = rt->children[tmp];
            i++;
        }
        rt->ct_val += content;
        rt->isFile = true;
    }
    
    string readContentFromFile(string filePath) {
        tnode* rt = root;
        int i = 1;
        while(i < filePath.size()){
            string tmp = "";
            while(i < filePath.size() && filePath[i] != '/'){
                tmp += filePath[i++];
            }
            rt = rt->children[tmp];
            i++;
        }
        return rt->ct_val;
    }
    private:
    tnode* root;
    };
    

    /**

    • Your FileSystem object will be instantiated and called as such:
    • FileSystem obj = new FileSystem();
    • vector<string> param_1 = obj.ls(path);
    • obj.mkdir(path);
    • obj.addContentToFile(filePath,content);
    • string param_4 = obj.readContentFromFile(filePath);
      */

Log in to reply
 

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