Python using Tree and Dict

  • 0
    class FileNode(object):
        def __init__(self, name):
            self.isFolder = True
            self.childs = {}
   = name
   = ""
        def appendData(self, data):
   += data
        def readAll(self):
    class FileSystem(object):
        def __init__(self):
            self.root = FileNode("/")
        def ls(self, path):
            fd = self.lookup(path, False)
            if not fd:
                return []
            if not fd.isFolder:
                return []
            files = []
            for file in fd.childs:
            return files
        def lookup(self, path, isAutoCreate):
            path = path.split("/")
            p = self.root
            for name in path:
                if not name:
                if name not in p.childs:
                    if isAutoCreate:
                        p.childs[name] = FileNode(name)
                        return None
                p = p.childs[name]
            return p
        def mkdir(self, path):
            self.lookup(path, True)
        def addContentToFile(self, filePath, content):
            fd = self.lookup(filePath, True)
            fd.isFolder = False
        def readContentFromFile(self, filePath):
            fd = self.lookup(filePath, False)
            if fd:
                return fd.readAll()
            return ""

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.