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:
def simplifyPath(path: str) -> str:
# Split the path by '/'
components = path.split('/')
stack = []
for component in components:
if component == '' or component == '.':
continue
elif component == '..':
if stack:
stack.pop()
else:
stack.append(component)
# Join the stack to form a canonical path
return '/' + '/'.join(stack)
# Test examples
print(simplifyPath("/home/")) # Output: "/home"
print(simplifyPath("/../")) # Output: "/"
print(simplifyPath("/home//foo/")) # Output: "/home/foo"
print(simplifyPath("/a/./b/../../c/")) # Output: "/c"
The given solution has a time complexity of O(N), where N is the length of the input path string. This is because:
Thus, the overall time complexity is O(N).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?