C++ fast no user defined types needed


  • 1
    Q
    class FileSystem {
    public:
    
    	unordered_map<string, set<string>> dTable;  // dir name to contents
    	unordered_map<string, string> fTable; //file name to contents 
    
    
    public:
    	FileSystem() {
    	    dTable["/"];
    	}
    
    	vector<string> ls(string path) {
    		vector<string> res;
    		if (fTable.find(path) != fTable.end())
    		{
    			int i = path.length() - 1;
    
    			while (i >= 0 && path[i] != '/') --i;
    
    			res.push_back(path.substr(i + 1));
    			return res;
    		}
    
    		if (dTable.find(path) != dTable.end())
    		{
    			for (auto s : dTable[path])
    				res.push_back(s);
    		}
    
    		return res;
    	}
    
    	void mkdir(string path) {
    		string prev = "/";
    		int prevPos = 1;
    		for (int i = 1; i <= path.size(); ++i)
    		{
    			if (path[i] == '/' || path[i] == 0)
    			{
    				dTable[prev].insert(path.substr(prevPos, i - prevPos));
    				prevPos = i+1;
    				prev = path.substr(0, i);
    			}
    		}
    	}
    
    	void addContentToFile(string filePath, string content) {
    
    		int i = filePath.length() - 1;
    
    		while (i >= 0 && filePath[i] != '/') --i;
    		
    		string path = filePath.substr(0, i);
    		string file = filePath.substr(i + 1);
    
    		if (path.empty()) path = "/";
    
    		if (dTable.find(path) == dTable.end())
    			mkdir(path);
    		
    		dTable[path].insert(file);
    
    		fTable[filePath].append(content);
    		
    	}
    
    	string readContentFromFile(string filePath) {
    		if (fTable.find(filePath) != fTable.end())
    			return fTable[filePath];
    		return "";
    	}
    };

  • 0
    G

    @QQBear said in C++ fast no user defined types needed:

    path[i] == 0

    Nice solution! Also, could you explain why put ' path[i] == 0' in the mkdir function?


  • 0
    Q

    @grandyang Looks like you are the first one to appreciate the solution :=). Thanks. Because the spec says "paths which begin with / and do not end with /", so the end of "path" (path[path.size()]==0) is equivalent to '/'.


Log in to reply
 

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