思路:
- 模拟栈操作,遇到目录名入栈,遇到
..
就出栈,那么,最后还在栈里面的,就是剩下的完整目录应有的各个目录名 -
代码:
class Solution:
def simplifyPath(self, path: str) -> str:
# 去掉重复的斜杠
items = [item for item in path.split(*'/') if item != '']
stack = []
for item in items:
if item == '.':
continue
elif item == '..':
if not stack:
continue
else:
stack.pop()
else:
stack.append(item)
return '/'+'/'.join(stack)