[LeetCode]Design In-Memory File System

题目描述:

LeetCode 588. Design In-Memory File System

Design an in-memory file system to simulate the following functions:

ls: Given a path in string format. If it is a file path, return a list that only contains this file's name. If it is a directory path, return the list of file and directory names in this directory. Your output (file and directory names together) should in lexicographic order.

mkdir: Given a directory path that does not exist, you should make a new directory according to the path. If the middle directories in the path don't exist either, you should create them as well. This function has void return type.

addContentToFile: Given a file path and file content in string format. If the file doesn't exist, you need to create that file containing given content. If the file already exists, you need to append given content to original content. This function has void return type.

readContentFromFile: Given a file path, return its content in string format.

Example:

Input: 
["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
[[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
Output:
[null,[],null,null,["a"],"hello"]
Explanation:
filesystem

Note:

  1. You can assume all file or directory paths are absolute paths which begin with / and do not end with / except that the path is just "/".
  2. You can assume that all operations will be passed valid parameters and users will not attempt to retrieve file content or list a directory or file that does not exist.
  3. You can assume that all directory names and file names only contain lower-case letters, and same names won't exist in the same directory.

题目大意:

设计内存文件系统模拟实现如下功能:

ls:给定路径字符串,若对应一个目录,则输出其中包含的目录和文件(字典序);若对应一个文件,则只输出该文件名

mkdir:创建目录,若目录不存在,则递归创建缺少的目录

addContentToFile:在文件中追加内容,若文件不存在,则新建

readContentFromFile:从文件中读取内容并返回

注意:

  1. 你可以假设文件和目录的路径均为绝对路径,以/开始,并且结尾不包含/,除非路径就是"/"本身
  2. 你可以假设所有操作均合法,用户不会常识读取一个不存在的文件,或者ls一个不存在的目录
  3. 你可以假设所有目录名称和文件名称都只包含小写字母,并且在同一目录下不会存在同名的目录或者文件

解题思路:

树形结构(Tree)

目录节点Node包含两个字段dirs和files,分别存储其中包含的子目录节点和文件内容

Python代码:

class FileSystem(object):

    def __init__(self):
        self.root = {'dirs' : {}, 'files': {}}

    def ls(self, path):
        """
        :type path: str
        :rtype: List[str]
        """
        node, type = self.getExistedNode(path)
        if type == 'dir': return sorted(node['dirs'].keys() + node['files'].keys())
        return [path.split('/')[-1]]

    def mkdir(self, path):
        """
        :type path: str
        :rtype: void
        """
        node = self.root
        for dir in filter(len, path.split('/')):
            if dir not in node['dirs']: node['dirs'][dir] = {'dirs' : {}, 'files': {}}
            node = node['dirs'][dir]

    def addContentToFile(self, filePath, content):
        """
        :type filePath: str
        :type content: str
        :rtype: void
        """
        dirs = filePath.split('/')
        path, file = '/'.join(dirs[:-1]), dirs[-1]
        self.mkdir(path)
        node, type = self.getExistedNode(path)
        if file not in node['files']: node['files'][file] = ''
        node['files'][file] += content

    def readContentFromFile(self, filePath):
        """
        :type filePath: str
        :rtype: str
        """
        dirs = filePath.split('/')
        path, file = '/'.join(dirs[:-1]), dirs[-1]
        node, type = self.getExistedNode(path)
        return node['files'][file]
        
    def getExistedNode(self, path):
        """
        :type path: str
        :rtype: str
        """
        node = self.root
        for dir in filter(len, path.split('/')):
            if dir in node['dirs']: node = node['dirs'][dir]
            else: return node, 'file'
        return node, 'dir'

# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.ls(path)
# obj.mkdir(path)
# obj.addContentToFile(filePath,content)
# param_4 = obj.readContentFromFile(filePath)

 

本文链接:http://bookshadow.com/weblog/2017/05/21/leetcode-design-in-memory-file-system/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论