美文网首页
leetcode 71 Simplify Path

leetcode 71 Simplify Path

作者: 机器学习与自然语言处理 | 来源:发表于2019-11-14 09:52 被阅读0次

用栈的思想来解决这个问题,遇到当前路径就跳过,遇到上一个路径,就删除上一个路径,剩下的情况直接入栈即可。

class Solution:
    def simplifyPath(self, path: str) -> str:
        
        stack = list()
        dirs = path.split("/")
        for dir in dirs:
            if not dir or dir == ".":
                continue
            if dir == "..":
                if stack:
                    stack.pop()
            else:
                stack.append(dir)
        return '/' + '/'.join(stack)
image.png

相关文章

网友评论

      本文标题:leetcode 71 Simplify Path

      本文链接:https://www.haomeiwen.com/subject/flilictx.html