借用栈去解决,按照' / '分割字符串, 遇到 ' . ' 以及空字符跳过,遇到' .. '从栈里弹出元素,其余入栈,最后如果栈空应该返回一个' / '
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
result = []
for p in path.split('/'):
if p == '' or p == '.':
continue
elif p == '..':
try:
result.pop()
except IndexError:
continue
else:
result.append(p)
if len(result)==0:
result = ['']
return '/'.join(['']+result)