[LeetCode] Design File System

1166. Design File System

You are asked to design a file system that allows you to create new paths and associate them with different values.

The format of a path is one or more concatenated strings of the form: / followed by one or more lowercase English letters. For example, “/leetcode” and “/leetcode/problems” are valid paths while an empty string “” and “/“ are not.

Implement the FileSystem class:

  • bool createPath(string path, int value) Creates a new path and associates a value to it if possible and returns true. Returns false if the path already exists or its parent path doesn’t exist.
  • int get(string path) Returns the value associated with path or returns -1 if the path doesn’t exist.
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
struct Trie{
unordered_map<string, Trie*> next;
int val = -1;

Trie(){}
bool insert(queue<string>& q, int v) {
if(q.empty()) {
if(val == -1) {
val = v; return true;
} else return false;
} else {
auto p = q.front(); q.pop();
if(!next.count(p) and q.empty()) next[p] = new Trie();
if(next.count(p)) return next[p]->insert(q, v);
return false;
}
}
int get(queue<string>& q) {
if(q.empty()) return val;
else {
auto p = q.front(); q.pop();
if(!next.count(p)) return -1;
return next[p]->get(q);
}
}
};
class FileSystem {
Trie* t;
public:
FileSystem() {
t = new Trie();
}

queue<string> pathQ(string& path) {
if(path.length() <= 1) return {};
queue<string> q;
int i = 1, n = path.length();
string s;
while(i < n) {
if(path[i] == '/') {
q.push(s);
s = "";
} else s.push_back(path[i]);
i++;
}
q.push(s);
return q;
}

bool createPath(string path, int value) {
auto q = pathQ(path);

return t->insert(q,value);
}

int get(string path) {
auto q = pathQ(path);

return t->get(q);
}
};

/**
* Your FileSystem object will be instantiated and called as such:
* FileSystem* obj = new FileSystem();
* bool param_1 = obj->createPath(path,value);
* int param_2 = obj->get(path);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/22/PS/LeetCode/design-file-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.