Skip to content

Commit 240980f

Browse files
committed
#71: Simplify Path
1 parent fbfbc5f commit 240980f

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Stacks/simplify_path.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# You are given an absolute path for a Unix-style file system, which always
2+
# begins with a slash '/'. Your task is to transform this absolute path into
3+
# its simplified canonical path.
4+
5+
# The rules of a Unix-style file system are as follows:
6+
7+
# A single period '.' represents the current directory.
8+
# A double period '..' represents the previous/parent directory.
9+
# Multiple consecutive slashes such as '//' and '///' are treated as a single slash '/'.
10+
# Any sequence of periods that does not match the rules above should be treated as
11+
# a valid directory or file name. For example, '...' and '....' are valid directory
12+
# or file names.
13+
# The simplified canonical path should follow these rules:
14+
15+
# The path must start with a single slash '/'.
16+
# Directories within the path must be separated by exactly one slash '/'.
17+
# The path must not end with a slash '/', unless it is the root directory.
18+
# The path must not have any single or double periods ('.' and '..') used to denote
19+
# current or parent directories.
20+
# Return the simplified canonical path.
21+
22+
23+
# Example 1:
24+
# Input: path = "/home/"
25+
# Output: "/home"
26+
27+
# Explanation:
28+
# The trailing slash should be removed.
29+
30+
# Example 2:
31+
# Input: path = "/home//foo/"
32+
# Output: "/home/foo"
33+
34+
# Explanation:
35+
# Multiple consecutive slashes are replaced by a single one.
36+
37+
# Example 3:
38+
# Input: path = "/home/user/Documents/../Pictures"
39+
# Output: "/home/user/Pictures"
40+
41+
# Explanation:
42+
# A double period ".." refers to the directory up a level (the parent directory).
43+
44+
# Example 4:
45+
# Input: path = "/../"
46+
# Output: "/"
47+
48+
# Explanation:
49+
# Going one level up from the root directory is not possible.
50+
51+
# Example 5:
52+
# Input: path = "/.../a/../b/c/../d/./"
53+
# Output: "/.../b/d"
54+
55+
# Explanation:
56+
# "..." is a valid name for a directory in this problem.
57+
58+
59+
60+
# Constraints:
61+
# 1 <= path.length <= 3000
62+
# path consists of English letters, digits, period '.', slash '/' or '_'.
63+
# path is a valid absolute Unix path.
64+
65+
66+
class Solution:
67+
def simplifyPath(self, path: str) -> str:
68+
stack = []
69+
token = path.split('/')
70+
for str in token:
71+
if str == '' or str == '.':
72+
continue
73+
if str == '..':
74+
if stack:
75+
stack.pop()
76+
else:
77+
stack.append(str)
78+
return '/'+'/'.join(stack)

0 commit comments

Comments
 (0)