1166. Design File System - cocoder39/coco39_LC GitHub Wiki

1166. Design File System

class TrieNode:
    def __init__(self, val = -1):
        self.root = None
        self.val = val
        self.children = {}

class FileSystem:

    def __init__(self):
        self.root = TrieNode()
        

    def createPath(self, path: str, value: int) -> bool:
        tokens = path.split('/')
        cur = self.root
        for i in range(1, len(tokens)-1):
            if tokens[i] not in cur.children:
                return False
            cur = cur.children[tokens[i]]
        
        if tokens[-1] in cur.children:
            return False
        cur.children[tokens[-1]] = TrieNode(value)
        return True
        
    def get(self, path: str) -> int:
        tokens = path.split('/')
        cur = self.root
        for i in range(1, len(tokens)):
            if tokens[i] not in cur.children:
                return -1
            cur = cur.children[tokens[i]]
        return cur.val