化简Unix系统下一个文件的绝对路径。 输入: path = “/a/./b/../../c/”
输出: “/c”
栈
参考: https://shenjie1993.gitbooks.io/leetcode-python/071%20Simplify%20Path.html
用栈来处理,碰到有效字符就压栈,遇到上层目录字符”..”且栈不空时就弹出。为了最后连接字符串时头上有根目录,在栈底加一个空字符。
>>> a= ['a','b','c']
>>> '/'.join(a)
'a/b/c'
>>> a = ['','a','b']
>>> '/'.join(a)
'/a/b
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
parts = path.split("/")
result = ['']
for part in parts:
if part:
if part not in ('.', '..'):
if len(result) == 0: # 若栈底空了,加入空字符再加入目录名
result.append('')
result.append(part)
elif part == '..' and len(result) > 0:
result.pop()
if len(result) < 2:
return "/"
else:
return "/".join(result) # 以/来组合list里的字符