588. Design In-Memory File System

LeetCode


Approach: Using separate Directory and File List[Accepted]

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
class FileSystem {
class Dir {
HashMap<String, Dir> dirs = new HashMap<>();
HashMap<String, String> files = new HashMap<>();
}

Dir root;

public FileSystem() {
root = new Dir();
}

public List<String> ls(String path) {
Dir t = root;
List<String> files = new ArrayList<>();
if (!path.equals("/")) {
String[] d = path.split("/");
for (int i = 1; i < d.length - 1; i++) {
t = t.dirs.get(d[i]);
}
if (t.files.containsKey(d[d.length - 1])) {
files.add(d[d.length - 1]);
return files;
} else {
t = t.dirs.get(d[d.length - 1]);
}
}
files.addAll(new ArrayList<>(t.dirs.keySet()));
files.addAll(new ArrayList<>(t.files.keySet()));
Collections.sort(files);
return files;
}

public void mkdir(String path) {
Dir t = root;
String[] d = path.split("/");
for (int i = 1; i < d.length; i++) {
if (!t.dirs.containsKey(d[i]))
t.dirs.put(d[i], new Dir());
t = t.dirs.get(d[i]);
}
}

public void addContentToFile(String filePath, String content) {
Dir t = root;
String[] d = filePath.split("/");
for (int i = 1; i < d.length - 1; i++) {
t = t.dirs.get(d[i]);
}
t.files.put(d[d.length - 1], t.files.getOrDefault(d[d.length - 1], "") + content);
}

public String readContentFromFile(String filePath) {
Dir t = root;
String[] d = filePath.split("/");
for (int i = 1; i < d.length - 1; i++) {
t = t.dirs.get(d[i]);
}
return t.files.get(d[d.length - 1]);
}
}

/**
* Your FileSystem object will be instantiated and called as such: FileSystem
* obj = new FileSystem(); List<String> param_1 = obj.ls(path); obj.mkdir(path);
* obj.addContentToFile(filePath,content); String param_4 =
* obj.readContentFromFile(filePath);
*/

0%