Python solution using 2 dictionaries storing folder and file


  • 0
    from collections import defaultdict
    class FileSystem(object):
    
        def __init__(self):
            self.folder = defaultdict(set)
            self.file = {}
    
        def ls(self, path):
            return sorted((self.folder.get(path,[]))) # in lexicographic order
    
    
        def mkdir(self, path):
            # get each folder
            folder = path.split("/")
            for i in xrange(len(folder)-1):
                if folder[i]:
                    self.folder["/".join(folder[:i+1])].add(str(folder[i+1]))
                else:# ""
                    self.folder["/"].add(str(folder[i+1]))
    
        def addContentToFile(self, filePath, content):
    
            #append to file content
            self.file[filePath] = self.file.get(filePath,"") + content
            folder = filePath.split("/")
            self.folder[filePath].add(folder[-1])
            for i in xrange(len(folder)-1):
                if folder[i]:
                    self.folder["/".join(folder[:i+1])].add(str(folder[i+1]))
                else:
                    self.folder["/"].add(str(folder[i+1]))
    
        def readContentFromFile(self, filePath):
            return self.file[filePath]
    

Log in to reply
 

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