题目:
题目链接: https://leetcode-cn.com/problems/simplify-path/
解题思路:
使用'/'切分字符串之后进行遍历,会遇到下面几种情况:
- 字符串为空,跳过
- 字符串为 '.',跳过
- 字符串为 '..',并且栈中有已入栈的数据,则将最后入栈的元素出栈
- 其余字符串认为是有效目录,进行入栈操作
代码实现:
class Solution:
def simplifyPath(self, path: str) -> str:
split_lst = path.split('/')
result_lst = []
for curr_dir in split_lst:
if not curr_dir:
continue
elif curr_dir == '.':
continue
elif curr_dir == '..':
if len(result_lst) > 0:
result_lst.pop()
else:
result_lst.append(curr_dir)
return '/' + '/'.join(result_lst)