本文主要是介绍Leetcode 1166. Design File System [Python],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用了字典树来做。需要注意的是,假设Path= “/path1/path2/path3” ,split('/)之后是["", "path1","path2", "path3" ], 路径之前会有一个空格。在创建Path的时候,只能是最后一个位置的路径名找不到,才能合法创建,也就是
class TrieNode:def __init__(self, key):self.key = keyself.child = {}self.value = Noneclass FileSystem:def __init__(self):self.root = TrieNode(None)def createPath(self, path: str, value: int) -> bool:root = self.rootpath = path.split('/')[1:]if not path:return Falsefor 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 createdreturn Falseif index == len(path)-1 and file in root.child: #the path already there.return Falseif 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 = valueelse:root = root.child[file]return Truedef get(self, path: str) -> int:root = self.rootpath = path.split('/')[1:]for index, file in enumerate(path):if file not in root.child:return -1root = 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的时候,否则要么是已经有路径,要么是在中途某个点就找不到,不能创建。
这篇关于Leetcode 1166. Design File System [Python]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!