- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path71.py
51 lines (41 loc) · 1.02 KB
/
71.py
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
42
43
44
45
46
47
48
49
50
51
'''
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
'''
classSolution(object):
defsimplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
result="/"
stack= []
index=0
whileindex<len(path):
ifpath[index] =='/':
index+=1
continue
curr_str=""
whileindex<len(path) andpath[index] !='/':
curr_str+=path[index]
index+=1
ifcurr_str=='.'orcurr_str=="":
index+=1
continue
elifcurr_str=="..":
ifstack:
stack.pop()
index+=1
else:
stack.append(curr_str)
index+=1
forindexinrange(len(stack)):
ifindex!=len(stack) -1:
result+=stack[index] +'/'
else:
result+=stack[index]
returnresult
# Time: O(N)
# Space: O(N)