版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013596119/article/details/82496777
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
Answer:
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack=[]
lenstack=0
plist=path.split("/")
for p in plist:
if p!="":
if p==".." and lenstack>0:
stack.pop()
lenstack-=1
elif p=="." or p=="..":
continue
else:
stack.append(p)
lenstack+=1
result=""
if lenstack==0:
return "/"
for p in stack:
result+="/"+p
return result