Link: 71. Simplify Path - Medium
Question
Restate the problem
Given a string, Unix-style absolute path, return simplified canonical path.
Method
Key idea
Split path by /, iterate each directory token, use a stack to simulate directory navigation, then rebuild the path.
Complexity
- Time Complexity: O(n)
- Space Complexity: O(n)
Edge case
"/"return"/""/../"→"/"(can’t go above root)- Tokens like
"..."are not special → keep them (folder name)
Code
class Solution:
def simplifyPath(self, path: str) -> str:
stack = []
for token in path.split("/"):
if token in ("", "."):
continue
if token == "..":
if stack:
stack.pop()
continue
else:
stack.append(token)
return "/" + "/".join(stack)