forked from csujedihy/lc-all-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign-in-memory-file-system.py
84 lines (71 loc) · 1.97 KB
/
design-in-memory-file-system.py
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
class FileNode(object):
def __init__(self, name):
self.isFolder = True
self.childs = {}
self.name = name
self.data = ""
def appendData(self, data):
self.data += data
def readAll(self):
return self.data
class FileSystem(object):
def __init__(self):
self.root = FileNode("/")
def ls(self, path):
"""
:type path: str
:rtype: List[str]
"""
fd = self.lookup(path, False)
if not fd:
return []
if not fd.isFolder:
return [fd.name]
files = []
for file in fd.childs:
files.append(file)
files.sort()
return files
def lookup(self, path, isAutoCreate):
path = path.split("/")
p = self.root
for name in path:
if not name:
continue
if name not in p.childs:
if isAutoCreate:
p.childs[name] = FileNode(name)
else:
return None
p = p.childs[name]
return p
def mkdir(self, path):
"""
:type path: str
:rtype: void
"""
self.lookup(path, True)
def addContentToFile(self, filePath, content):
"""
:type filePath: str
:type content: str
:rtype: void
"""
fd = self.lookup(filePath, True)
fd.isFolder = False
fd.appendData(content)
def readContentFromFile(self, filePath):
"""
:type filePath: str
:rtype: str
"""
fd = self.lookup(filePath, False)
if fd:
return fd.readAll()
return ""
# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.ls(path)
# obj.mkdir(path)
# obj.addContentToFile(filePath,content)
# param_4 = obj.readContentFromFile(filePath)