forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 588.Design-In-Memory-File-System.cpp
- Loading branch information
1 parent
868e33e
commit 32aae47
Showing
1 changed file
with
86 additions
and
0 deletions.
There are no files selected for viewing
86 changes: 86 additions & 0 deletions
86
Trie/588.Design-In-Memory-File-System/588.Design-In-Memory-File-System.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
class FileSystem { | ||
class TrieNode | ||
{ | ||
public: | ||
map<string,TrieNode*>Map; | ||
bool isFile; | ||
}; | ||
TrieNode* root; | ||
unordered_map<string,string>FileContents; | ||
|
||
public: | ||
FileSystem() | ||
{ | ||
root=new TrieNode(); | ||
} | ||
|
||
vector<string> ls(string path) | ||
{ | ||
TrieNode* node=root; | ||
string str; | ||
for (int i=1; i<path.size(); i++) | ||
{ | ||
int i0=i; | ||
while (i<path.size() && path[i]!='/') | ||
i++; | ||
str=path.substr(i0,i-i0); | ||
node=node->Map[str]; | ||
} | ||
|
||
if (node->isFile) | ||
return {str}; | ||
else | ||
{ | ||
vector<string>results; | ||
for (auto a:node->Map) | ||
results.push_back(a.first); | ||
return results; | ||
} | ||
} | ||
|
||
void mkdir(string path) | ||
{ | ||
TrieNode* node=root; | ||
for (int i=1; i<path.size(); i++) | ||
{ | ||
int i0=i; | ||
while (i<path.size() && path[i]!='/') | ||
i++; | ||
string str=path.substr(i0,i-i0); | ||
if (node->Map.find(str)==node->Map.end()) | ||
node->Map[str]=new TrieNode(); | ||
node=node->Map[str]; | ||
} | ||
} | ||
|
||
void addContentToFile(string filePath, string content) | ||
{ | ||
TrieNode* node=root; | ||
for (int i=1; i<filePath.size(); i++) | ||
{ | ||
int i0=i; | ||
while (i<filePath.size() && filePath[i]!='/') | ||
i++; | ||
string str=filePath.substr(i0,i-i0); | ||
if (node->Map.find(str)==node->Map.end()) | ||
node->Map[str]=new TrieNode(); | ||
node=node->Map[str]; | ||
} | ||
node->isFile=1; | ||
FileContents[filePath]+=content; | ||
} | ||
|
||
string readContentFromFile(string filePath) | ||
{ | ||
return FileContents[filePath]; | ||
} | ||
}; | ||
|
||
/** | ||
* Your FileSystem object will be instantiated and called as such: | ||
* FileSystem obj = new FileSystem(); | ||
* vector<string> param_1 = obj.ls(path); | ||
* obj.mkdir(path); | ||
* obj.addContentToFile(filePath,content); | ||
* string param_4 = obj.readContentFromFile(filePath); | ||
*/ |