기술(Tech, IT)/리트코드(LeetCode)

[LeetCode] 1166. Design File System

Daniel803 2023. 7. 20. 02:36

 createPath 함수에 주어지는 input 중 하나인 path를 '/'로 split해 parent path와 비교해가며 함수를 완성하려 했지만, Test case에 번번히 걸려 다른 방법으로 풀었다. split을 통해 '/'로 path를 자르는건 동일하지만 split 된 list에서 마지막 요소만 제외하고 하나의 String으로 다시 구성해 parent에 대한 True/False를 확인하는 방식으로 풀었다.

 get 함수는 Hash map을 통해 수월하게 구현했다.

class FileSystem:
    def __init__(self):
        self.p = {}

    def createPath(self, path: str, value: int) -> bool:
        if path in self.p:
            return False

        ppath = path.split('/')
        ppath = '/'.join(ppath[:-1])

        if ppath not in self.p and ppath != '':
            return False

        self.p[path] = value

        return True

    def get(self, path: str) -> int:
        if path in self.p:
            return self.p[path]
        return -1