题意: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".
思路:这题开始时题意有点模糊,仔细理解就是化简linux的路径,也就是根据’.’,’..’走到字符串所要表达的真正路径上。利用堆栈,碰到’..’pop就好了。
代码:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
string = [i for i in path.strip().split('/') if i]
stack = []
for i in string:
if i=='..':
if len(stack):
stack.pop()
else:
continue
elif i!='.':
stack.append(i)
print stack
return '/'+'/'.join(stack)