71. Simplify Path
Given a string
path, which is an absolute path (starting with a slash
'/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period
'.' refers to the current directory, a double period
'..' refers to the directory up a level, and any multiple consecutive slashes (i.e.
'//') are treated as a single slash
'/'. For this problem, any other format of periods such as
'...' are treated as file/directory names.
The canonical path should have the following format:
- The path starts with a single slash
- Any two directories are separated by a single slash
- The path does not end with a trailing
- The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period
'.'or double period
Return the simplified canonical path.
The first task is to split the given input based on “/”. When we split the path, we can get separate folder names and “.” as well as “..” which represent the current directory and previous directory respectively.
We need a stack that keeps track of which folders need to be visited and what folders have to be skipped in the canonical path.
After we have finished splits the input path, we would have to compare each word with few things. If the word is empty or a “.”, it means we will be in the current folder itself. We would not be adding or removing any folder. If the current word is “..” we will have to pop the topmost folder from the stack. If the word is none of the above words, then we will be pushed into the stack.
Let us look into the code snippet.
def simplifyPath(self, path: str) -> str:
path_split = path.split('/')
output = ""
stack = 
for words in path_split:
if words == "" or words == ".":
elif words == "..":
for word in stack:
output = output + "/" + word
return output if output else "/"
We are visiting each folder in the path after we split based on “/”. Hence the time complexity is O(N), where N is the number of words.
We are using a stack inorder to store the names of the folders. Hence the space complexity is O(N), where N is the number of folders.