Simple C++ solution, use tree


  • 0
    V
    class FileSystem {
    public:
        FileSystem() {
            root = new Node();
        }
        
        vector<string> ls(string path) {
            Node *node = find_path(root, path, 0, 0);
            vector<string> ans;
            if (node == NULL) {
                return ans;
            }
            if (node->is_file) {
                ans.push_back(node->name);
            }
            else {
                for (auto &p : node->mp) {
                    ans.push_back(p.first);
                }
            }
            return ans;
        }
        
        void mkdir(string path) {
            find_path(root, path, 1, 0);
        }
        
        void addContentToFile(string filePath, string content) {
            Node *node = find_path(root, filePath, 1, 1);
            node->content += content;
        }
        
        string readContentFromFile(string filePath) {
            Node *node = find_path(root, filePath, 1, 1);
            return node->content;
        }
    private:
        struct Node {
            bool is_file;
            map<string, Node*> mp;
            string content;
            string name;
            Node():is_file(0) {}
        };
        Node *root;
        
        Node *find_path(Node *now, string path, bool need_create, bool is_file) {
            if (path == "/") {
                return now;
            }
            string rec;
            for (int i = 1; i <= path.size(); ++i) {
                if (i == path.size() || path[i] == '/') {
                    if (now->mp.find(rec) == now->mp.end()) {
                        if (!need_create) {
                            return NULL;
                        }
                        now->mp[rec] = new Node();
                    }
                    now = now->mp[rec];
                    if (i == path.size() && is_file) {
                        now->name = rec;
                    }
                    rec = "";
                }
                else {
                    rec += path[i];
                }
            }
            if (is_file) {
                now->is_file = 1;
            }
            return now;
        }
    };
    

Log in to reply
 

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