Python easy and fast solution - dict tree


  • 0
    D

    Use a dictionary tree to store the directories and the files as well

    class FileSystem(object):
    
        def __init__(self):
            self.root = {}
            
        def ls(self, path):
            """
            :type path: str
            :rtype: List[str]
            """
            arr = path.split("/")
            current = self.root
            for x in arr:
                if x == '':
                    continue
                if isinstance(current.get(x), dict):
                    current = current.get(x)
            if isinstance(current.get(arr[-1]), str):
                return [arr[-1]]
            return sorted(current.keys())
    
    
        def mkdir(self, path):
            """
            :type path: str
            :rtype: void
            """
            current = self.root
            for x in filter(None, path.split("/")):
                if x not in current:
                    current[x] = {}
                current = current.get(x)
    
        def addContentToFile(self, filePath, content):
            """
            :type filePath: str
            :type content: str
            :rtype: void
            """
            arr = filePath.split("/")
            current = self.root
            for x in arr[:-1]:
                if x == '':
                    continue
                current = current.get(x)
            file_name = arr[-1]
            if file_name not in current:
                current[file_name] = content
            else:
                current[file_name] += content
            
    
        def readContentFromFile(self, filePath):
            """
            :type filePath: str
            :rtype: str
            """
            current = self.root
            for x in filter(None, filePath.split("/")):
                current = current.get(x)
            return current
    

Log in to reply
 

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