用了字典树来做。需要注意的是,假设Path= “/path1/path2/path3” ,split('/)之后是["", "path1","path2", "path3" ], 路径之前会有一个空格。在创建Path的时候,只能是最后一个位置的路径名找不到,才能合法创建,也就是
class TrieNode:
def __init__(self, key):
self.key = key
self.child = {}
self.value = None
class FileSystem:
def __init__(self):
self.root = TrieNode(None)
def createPath(self, path: str, value: int) -> bool:
root = self.root
path = path.split('/')[1:]
if not path:return False
for index, file in enumerate(path):
if index != len(path) - 1 and file not in root.child: # not such path. Path missing before the new path created
return False
if index == len(path)-1 and file in root.child: #the path already there.
return False
if index == len(path)- 1 and file not in root.child: # the new path could only be created when the last file is new and all files before already there including creat the path from the root.
root.child[file] = TrieNode(file)
root = root.child[file]
root.value = value
else:
root = root.child[file]
return True
def get(self, path: str) -> int:
root = self.root
path = path.split('/')[1:]
for index, file in enumerate(path):
if file not in root.child:
return -1
root = root.child[file]
return root.value
# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.createPath(path,value)
# param_2 = obj.get(path)
index == length - 1的时候,否则要么是已经有路径,要么是在中途某个点就找不到,不能创建。