-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0588-design-in-memory-file-system.py
More file actions
70 lines (59 loc) · 1.84 KB
/
0588-design-in-memory-file-system.py
File metadata and controls
70 lines (59 loc) · 1.84 KB
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
# time complexity:
# ls: O(D + K log K)
# mkdir: O(D)
# addContentToFile: O(D + L)
# readContentFromFile: O(D + L)
# space complexity: O(N + T)
# N = number of directories/files
# T = total length of all file contents
from typing import List
class Dir:
def __init__(self):
self.dirs = {}
self.files = {}
class FileSystem:
def __init__(self):
self.root = Dir()
def ls(self, path: str) -> List[str]:
root = self.root
files = []
if path != "/":
d = path.split("/")
for i in range(1, len(d) - 1):
root = root.dirs[d[i]]
if d[-1] in root.files:
files.append(d[-1])
return files
else:
root = root.dirs[d[-1]]
files.extend(root.dirs.keys())
files.extend(root.files.keys())
files.sort()
return files
def mkdir(self, path: str) -> None:
root = self.root
d = path.split("/")
for i in range(1, len(d)):
if d[i] not in root.dirs:
root.dirs[d[i]] = Dir()
root = root.dirs[d[i]]
def addContentToFile(self, filePath: str, content: str) -> None:
root = self.root
d = filePath.split("/")
for i in range(1, len(d) - 1):
root = root.dirs[d[i]]
if d[-1] not in root.files:
root.files[d[-1]] = ""
root.files[d[-1]] += content
def readContentFromFile(self, filePath: str) -> str:
root = self.root
d = filePath.split("/")
for i in range(1, len(d) - 1):
root = root.dirs[d[i]]
return root.files[d[-1]]
fileSystem = FileSystem()
print(fileSystem.ls("/"))
fileSystem.mkdir("/a/b/c")
fileSystem.addContentToFile("/a/b/c/d", "hello")
print(fileSystem.ls("/"))
print(fileSystem.readContentFromFile("/a/b/c/d"))