Canonical Directory After CD Commands
Problem statement
Start in the root directory /. Execute each path operand in commands as one directory-change operation, then return the final canonical absolute path.
- An operand beginning with
/starts from root; any other operand starts from the current directory. - Split an operand at each
/. Ignore empty segments and the exact segment.. The exact segment..moves to the parent directory, but root has no parent. - Every other segment is a literal directory name, including
...and..... The paths describe navigation only; filesystem existence is not checked.
The result begins with one slash, has one slash between names, and has no trailing slash unless it is root. Return / when there are no commands.
Function
cdPath(commands: String[]) → StringExamples
Example 1
commands = ["projects/ml", "../vision", "/tmp//a/./", "../../logs"]return = "/logs"The third command resets to /tmp/a. The final two parent segments reach root before logs is added.
Example 2
commands = ["../../", "a/../b", "./c"]return = "/b/c"Parent steps at root stay at root; the later relative commands enter b then c.
Example 3
commands = ["x/.../y", "../z"]return = "/x/.../z"Three periods form a literal directory name, unlike the exact parent token ..
Example 4
commands = []return = "/"With no commands the current directory remains root.
Constraints
0 <= commands.length <= 10000.- Each operand is nonempty; the total number of characters is at most
100000. - Operands contain English letters, digits, underscores, periods, and slashes only.