zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Simplify Path(简化路径)

    Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

    Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

    Example 1:

    Input: "/home/"
    Output: "/home"
    Explanation: Note that there is no trailing slash after the last directory name.
    

    Example 2:

    Input: "/../"
    Output: "/"
    Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
    

    Example 3:

    Input: "/home//foo/"
    Output: "/home/foo"
    Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
    

    Example 4:

    Input: "/a/./b/../../c/"
    Output: "/c"
    

    Example 5:

    Input: "/a/../../b/../c//.//"
    Output: "/c"
    

    Example 6:

    Input: "/a//b////c/d//././/.."
    Output: "/a/b/c"

    思路

           对于python 的解法而言,我们可以先使用"/"将路径进行分割得到一个列表,设置一个辅助空间栈,然后遍历次列表,如果当前结果为'..',栈不为空弹出栈顶元素,为空则不执行操作。如果为'.',则不进行操作,否则将其添加进栈中。时间复杂度为O(n), 空间复杂度为O(n)。
    解决代码

    
    
     1 class Solution(object):
     2     def simplifyPath(self, path):
     3         """
     4         :type path: str
     5         :rtype: str
     6         """
     7         places = [p for p in path.split("/") if p!="." and p!=""]  # 先将字符串以'/'进行分割,然后进行条件筛选。
     8         stack = []
     9         for p in places:
    10             if p == "..":     # 判断栈是否为空,不为空则弹出栈顶的元素
    11                 if len(stack) > 0:
    12                     stack.pop()
    13             else:
    14                 stack.append(p)
    15         return "/" + "/".join(stack) # 重新进行组合
  • 相关阅读:
    xshell入门及Linux常用命令
    C++之vector
    c++ 之 string
    引用 与 指针
    关于时间复杂度的计算以及相关概念
    位运算
    thymeleafDemo
    面试总结
    关于mvvm原理实现,模拟vue(3)-----发布订阅
    关于mvvm原理实现,模拟vue(2)-----模板编译
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10771056.html
Copyright © 2011-2022 走看看