You are given an absolute path in a Unix-style file system. Rewrite it in canonical form by resolving the special directory names and removing redundant separators.
Function Signature
def canonicalize_path(path: str) -> str:
Rules
-
The input always starts with
/
. Split it into components on
/
; any run of consecutive slashes counts as a single separator, and empty components are ignored.
-
A component equal to
.
refers to the current directory and is dropped.
-
A component equal to
..
moves up to the parent directory, removing the most recently kept name. At the root there is no parent, so
..
leaves the path at the root.
-
Every other component is an ordinary directory or file name, including names made only of periods such as
...
or
....
.
-
The canonical path starts with exactly one
/
, joins the kept names with single
/
characters, and has no trailing
/
. If no names remain, the result is
/
.
Constraints
-
1 <= len(path) <= 3000
-
path[0] == "/"
-
path
contains only English letters, digits,
.
,
/
and
_
.
Examples
Example 1
Input: path = "/usr//local/./bin/"
Output: "/usr/local/bin"
The doubled slash collapses, the . component is dropped and the trailing slash is removed.
Example 2
Input: path = "/a/b/../../../c/.../d/.."
Output: "/c/..."
The first two .. components undo b and a; the third is applied at the root and has no effect. ... is an ordinary name, and the final .. undoes d.
Example 3
Input: path = "/../"
Output: "/"