-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathsimplify_path.py
More file actions
41 lines (32 loc) · 902 Bytes
/
simplify_path.py
File metadata and controls
41 lines (32 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""
Simplify Path
Given an absolute Unix-style file path, simplify it by resolving '.'
(current directory), '..' (parent directory), and multiple slashes.
Reference: https://leetcode.com/problems/simplify-path/
Complexity:
Time: O(n)
Space: O(n)
"""
from __future__ import annotations
def simplify_path(path: str) -> str:
"""Simplify a Unix-style absolute path.
Args:
path: An absolute file path string.
Returns:
The simplified canonical path.
Examples:
>>> simplify_path("/home/")
'/home'
>>> simplify_path("/a/./b/../../c/")
'/c'
"""
skip = {"..", ".", ""}
stack: list[str] = []
tokens = path.split("/")
for token in tokens:
if token == "..":
if stack:
stack.pop()
elif token not in skip:
stack.append(token)
return "/" + "/".join(stack)