71. Simplify Path
Problem description:
Given an absolute path for a file (Unix-style), simplify it.
For example1
2
3
4path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"
In a UNIX-style file system, a period (‘.’) refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period (“..”) moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style
Corner Cases:
Did you consider the case where path = “/../“?
In this case, you should return “/“.
Another corner case is the path might contain multiple slashes ‘/‘ together, such as “/home//foo/“.
In this case, you should ignore redundant slashes and return “/home/foo”.
Solution:
The idea is to think of we need to keep the visited paths in a way that we could easily find the last one(need to go back one directory if we meet ..
).
Then we can make the pushing to stack more strict, ie: only pushing the things we want into stack. So we don’t need to push .
into stack.
Another thing to mention in python is the join
, separator.join(iterable)
1 | class Solution: |
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(n)$
reference: