C++ Clean Solution + Explanation


  • 0
    B

    We build a trie and travel down it in each function. We reuse function mkdir to travel down our trie by using a private variable ptr, so that ptr always points to the end leaf of the trie after mkdir is called. Also, for function ls, the names are automatically sorted in map when we build our trie.

    class FileSystem {
    private:
        struct trie {
            map<string,trie*> next;
            bool isfile;
            string filename;
            string contents;
            trie() {
                isfile=false;
                contents="";
            }
        };
        // set *ptr as a variable that can used by other functions after mkdir is called
        trie *root,*ptr;
    public:
        FileSystem() {
            root = new trie();
        }
        
        vector<string> ls(string path) {
            vector<string> res;
            mkdir(path); // travel down path
            if (ptr->isfile) return {ptr->filename};
            for (pair<string,trie*> p:ptr->next) res.push_back(p.first);
            return res;
        }
        
        void mkdir(string path) {
            istringstream ipath=istringstream(path);
            string dir;
            getline(ipath,dir,'/'); // for first '/'
            ptr=root;
            while (getline(ipath,dir,'/')) {
                if (!ptr->next.count(dir)) ptr->next[dir]=new trie();
                ptr=ptr->next[dir];
            }
        }
        
        void addContentToFile(string filePath, string content) {
            mkdir(filePath); // travel down filePath
            ptr->isfile=true;
            ptr->contents+=content;
            
            // get file name
            string fname="";
            while (filePath.back()!='/') {
                fname=filePath.back()+fname;
                filePath.pop_back();
            }
            ptr->filename=fname;
        }
        
        string readContentFromFile(string filePath) {
            mkdir(filePath); // travel down filePath
            return ptr->contents;
        }
    };
    

Log in to reply
 

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