描述
给定一个文档(Unix-style)的完全路径,请进行路径简化。
您在真实的面试中是否遇到过这个题? 是
样例
"/home/"
, => "/home"
"/a/./b/../../c/"
, => "/c"
挑战
-
你是否考虑了 路径 =
"/../"
的情况?在这种情况下,你需返回
"/"
。 -
此外,路径中也可能包含双斜杠
'/'
,如"/home//foo/"
。在这种情况下,可忽略多余的斜杠,返回
"/home/foo"
。
实现代码:
class Solution:
"""
@param path: the original path
@return: the simplified path
"""
def simplifyPath(self, path):
# write your code here
stack = []
for item in path.split('/'):
#当出现了/../的情况下,返回/,即清空stack
if item == '..':
while stack:
stack.pop()
elif item == '.':
pass
#将路径值都加入stack
elif item:
stack.append(item)
return '/' + '/'.join(stack)