美文网首页
8.27 - hard - 106

8.27 - hard - 106

作者: 健时总向乱中忙 | 来源:发表于2017-08-28 08:51 被阅读0次

588. Design In-Memory File System

一道设计题,还挺有意思的,可以再搞一遍

def path_split(path):
    return [frag for frag in path.split('/') if frag.strip() != '']

class FileSystem(object):

    def __init__(self):
        self.fs = {}
        
    def ls(self, path):
        """
        :type path: str
        :rtype: List[str]
        """
        curr = self.fs
        frags = path_split(path)
        for frag in frags:
            if frag not in curr:
                curr[frag] = {}
            curr = curr[frag]
            if type(curr) == unicode:
                return [frags[-1]]
        return sorted(curr.keys())
        

    def mkdir(self, path):
        """
        :type path: str
        :rtype: void
        """
        curr = self.fs
        frags = path_split(path)
        for frag in frags:
            if frag not in curr:
                curr[frag] = {}
            curr = curr[frag]
        

    def addContentToFile(self, filePath, content):
        """
        :type filePath: str
        :type content: str
        :rtype: void
        """
        curr = self.fs
        frags = path_split(filePath)
        for frag in frags[:-1]:
            if frag not in curr:
                curr[frag] = {}
            curr = curr[frag]
        file_name = frags[-1]
        if file_name not in curr:
            curr[file_name] = ''
        curr[file_name] += content
        

    def readContentFromFile(self, filePath):
        """
        :type filePath: str
        :rtype: str
        """
        curr = self.fs
        frags = path_split(filePath)
        for frag in frags[:-1]:
            if frag not in curr:
                curr[frag] = {}
            curr = curr[frag]
        file_name = frags[-1]
        return curr[file_name]
        


# 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)

相关文章

  • 8.27 - hard - 106

    588. Design In-Memory File System 一道设计题,还挺有意思的,可以再搞一遍

  • 8.27 - hard - 108

    600. Non-negative Integers without Consecutive Ones 这题的递推...

  • 8.27 - hard - 107

    591. Tag Validator 不太理解这道题的意义何在?? 直接抄了答案,并且不太想去理解答案,等到复习的...

  • 8.27 - hard - 109

    629. K Inverse Pairs Array递推公式如下f(n,k) = sum(f(n-1,i)), w...

  • 8.27 - hard - 110

    630. Course Schedule III 现排序,再用heap,很多greedy的问题都可以这样来做。基本...

  • 8.27棕色

  • 19/09/2017

    Work hard,play hard,study hard, love hard.一个小姐姐跟我这么说。她说后两...

  • 英文书法练习~learning

    learning is sometimes hard, But hard is not impossible.学习...

  • 你辛苦了。

    Thanks for your hard work. 重读:hard

  • 他对我很不客气。

    He is very hard / on me. 重读:hard

网友评论

      本文标题:8.27 - hard - 106

      本文链接:https://www.haomeiwen.com/subject/lwdwdxtx.html