【leetcode系列】【算法】【中等】简化路径

题目:

题目链接: https://leetcode-cn.com/problems/simplify-path/

解题思路:

使用'/'切分字符串之后进行遍历,会遇到下面几种情况:

  1. 字符串为空,跳过
  2. 字符串为 '.',跳过
  3. 字符串为 '..',并且栈中有已入栈的数据,则将最后入栈的元素出栈
  4. 其余字符串认为是有效目录,进行入栈操作

代码实现:

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)
发布了100 篇原创文章 · 获赞 4 · 访问量 1490

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105236115