-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path71_Simplify_Path.py
46 lines (42 loc) · 1.03 KB
/
71_Simplify_Path.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
class Solution:
def simplifyPath(self,path):
stack=[]
i=0
res=''
while i<len(path):
end = i+1
while end<len(path) and path[end]!="/":
end+=1
sub=path[i+1:end]
if len(sub)>0:
if sub=="..":
if stack !=[]:stack.pop()
elif sub!=".":
stack.append(sub)
i=end
if stack==[]:return "/"
for i in stack:
res+="/"+i
return res
class Solution2:
def simplifyPath(self,path):
path=path.split('/')
cur='/'
for i in path:
if i=='..':
if cur!='/':
cur='/'.join(cur.split('/')[:-1])
if cur=='':cur='/'
elif i!='.' and i!='':
cur+='/'+i if cur!='/' else i
return cur
if __name__=="__main__":
print Solution().simplifyPath("/home/")
print Solution().simplifyPath("/a/./b/../../c/")
print Solution().simplifyPath("/../")
print Solution().simplifyPath("/home//foo/")
print '-'*50
print Solution2().simplifyPath("/home/")
print Solution2().simplifyPath("/a/./b/../../c/")
print Solution2().simplifyPath("/../")
print Solution2().simplifyPath("/home//foo/")