【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) # 重新进行组合