share my solution using only vector and unordered_map


  • 0
    M
    class FileSystem {
    public:
        typedef struct inode{
            int i;
            int type;
        }inode;
        
        vector<unordered_map<string,inode>> dirs;
        vector<string> files;
    
        FileSystem() {
            dirs.push_back({});
        }
        
        vector<string> ls(string path) {
            string dir;
            stringstream ss(path.substr(1));
            int i = 0;
    
            while(getline(ss,dir,'/')){
                if(dirs[i].count(dir)){
                    int type = dirs[i][dir].type;
                    if(type == 1){
                            return {dir};
                    }else{
                        i = dirs[i][dir].i;
                    }
                }
            }
            
            vector<string> res;
            for(auto e : dirs[i]){
                res.push_back(e.first);
            }
            sort(res.begin(), res.end());
            return res;
           
        }
        
        void mkdir(string path) {
            string dir;
            char delim;
            stringstream ss(path.substr(1));
            int i = 0;
            while(getline(ss, dir, '/')){
                if(!dirs[i].count(dir)){
                    int n = dirs.size();
                    dirs.push_back({});
                    dirs[i].insert({dir, {n, 0}});
                }
                i = dirs[i][dir].i;
            }
           
        }
        
        void addContentToFile(string filePath, string content) {
            string dir;
            stringstream ss(filePath.substr(1));
            int i = 0;
            while(getline(ss, dir, '/')){
                
                if(dirs[i].count(dir)){
                    if(dirs[i][dir].type == 0)
                         i = dirs[i][dir].i;
                    else
                        files[dirs[i][dir].i] += content;
                }else{
                    int n = files.size();
                    files.push_back(content);
                    dirs[i][dir] = {n, 1};
                }
            }
           
        }
        
        string readContentFromFile(string filePath) {
            string dir;
            stringstream ss(filePath.substr(1));
            int i = 0;
            string res;
    
            while(getline(ss, dir, '/')){
                //std::cout << dir << std::endl;
                
                if(dirs[i][dir].type == 0){
                    i = dirs[i][dir].i;
                }else{
                    res = files[dirs[i][dir].i];
                }
            }
            
            return res;
        }
    };
    
    

Log in to reply
 

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