forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-in-memory-file-system.cpp
93 lines (79 loc) · 2.46 KB
/
design-in-memory-file-system.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Time: ls: O(l + klogk), l is the path length, k is the number of entries in the last level directory
// mkdir: O(l)
// addContentToFile: O(l + c), c is the content size
// readContentFromFile: O(l + c)
// Space: O(n + s), n is the number of dir/file nodes, s is the total content size.
class FileSystem {
public:
FileSystem() : root_(new TrieNode()) {
}
vector<string> ls(string path) {
auto curr = getNode(path);
if (curr->isFile) {
return {split(path, '/').back()};
}
vector<string> result;
for (const auto& child : curr->children) {
result.emplace_back(child.first);
}
sort(result.begin(), result.end());
return result;
}
void mkdir(string path) {
auto curr = putNode(path);
curr->isFile = false;
}
void addContentToFile(string filePath, string content) {
auto curr = putNode(filePath);
curr->isFile = true;
curr->content += content;
}
string readContentFromFile(string filePath) {
return getNode(filePath)->content;
}
private:
struct TrieNode {
bool isFile;
unordered_map<string, TrieNode *> children;
string content;
};
TrieNode *root_;
TrieNode *getNode(const string& path) {
vector<string> strs = split(path, '/');
auto curr = root_;
for (const auto& str : strs) {
curr = curr->children[str];
}
return curr;
}
TrieNode *putNode(const string& path) {
vector<string> strs = split(path, '/');
auto curr = root_;
for (const auto& str : strs) {
if (!curr->children.count(str)) {
curr->children[str] = new TrieNode();
}
curr = curr->children[str];
}
return curr;
}
vector<string> split(const string& s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
while (getline(ss, token, delim)) {
if (!token.empty()) {
tokens.emplace_back(token);
}
}
return tokens;
}
};
/**
* 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);
*/