[Leetcode] 71. Simplify Path

whitehousechef·2025년 8월 24일

https://leetcode.com/problems/simplify-path/description/

initial

needed some time to think of using the split pattern but solved it but not really clean like i didnt use join at last part

class Solution:
    def simplifyPath(self, path: str) -> str:
        ans="/"
        stack =[]
        lst = path.split("/")
        print(lst)
        for i in lst:
            if i:
                if i==".":
                    continue
                elif i=="..":
                    if stack:
                        stack.pop()
                else:
                    stack.append(i)

        while stack:
            ans+=stack.pop(0)
            ans+="/"
        return ans[:-1] if len(ans)>1 else ans

cleaner code sol

    def simplifyPath(self, path: str) -> str:
        stack = []
        
        for part in path.split("/"):
            if part in ("", "."):  # skip empty or current dir
                continue
            elif part == "..":
                if stack:
                    stack.pop()
            else:
                stack.append(part)
        
        return "/" + "/".join(stack)

hard follow up

so there can be nested alias

path = "/home/@subpath1/foo/"

path_mapping = {
	"@subpat1": "/a/@subpat2/v",
    "@subpat2": "/21/../2232"
}

so we need to recursively act if theres nested alias

def simplifyPath(unprocessed_path, path_mapping) -> str:
    stack = []
    def process(path,visited):
        nonlocal stack

        for part in path.split("/"):
            if part in ("", "."):  # skip empty or current dir
                continue
            elif part == "..":
                if stack:
                    stack.pop()
            elif "@" in part:
                if part in visited:
                    raise ValueError("already visited")
                subparts = path_mapping.get(part, "").split("/")
                visited.add(part)
                process("/".join(subparts),visited)
                visited.remove(part)
            else:
                stack.append(part)

        return "/" + "/".join(stack)
    return process(unprocessed_path,set())

path_mapping = {
    "@foo": "a/b",
    "@bar": "@foo/../c"
}

print(simplifyPath("/x/@bar/d", path_mapping))
# Output: /x/c/d

complexity

n time and space

0개의 댓글