C++


  • 0
    J
    class FileSystem {
    public:
        FileSystem() {
            
        }
        
        vector<string> ls(string path) {
            vector<string> res;
            if(files.count(path))//注意这个是文件名。
            {
                int idx = path.find_last_of('/');
                return {path.substr(idx+1)};
            }
            set<string> dir = dirs[path];
            return vector<string>(dir.begin(),dir.end());
        }
        
        void mkdir(string path) {
             istringstream is(path+"/");
             string token,dir="";
             while(getline(is,token,'/'))
             {
                 if(token.empty())continue;
                 if(dir.empty()) dir ="/";//这个如果是空,就是根目录。
                 dirs[dir].insert(token);
                 if(dir.size()>1) dir+="/";
                 dir+=token;
             }
        }
        
        void addContentToFile(string filePath, string content) {
            int pos = filePath.find_last_of("/");
            string dir = filePath.substr(0,pos);
            string file = filePath.substr(pos+1);
            if(dir.empty()) dir="/";//这个如果是空,就是根目录。
            if(dirs.find(dir)==dirs.end()) mkdir(dir);
            dirs[dir].insert(file);
            files[filePath].append(content);
        }
        
        string readContentFromFile(string filePath) {
             return files[filePath];
        }
    private:
        unordered_map<string,set<string>> dirs;
        unordered_map<string,string>files;
    };
    

Log in to reply
 

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