Engineering platform~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-71stacks
A build tool receives file paths typed by people and scripts. Before it caches a result, it rewrites each path to one standard form, so that two paths that lead to the same folder look the same.
A path starts with /, the root. A part . means the current folder, and .. means the parent folder. Several slashes in a row count as one. A path can have up to 100,000 characters.
Write clean_path(path).
path starts with /. It is made of parts separated by one or more /. A part is made of the letters a to z and dots.. means stay where you are. A part .. means go up one folder, and at the root it does nothing. Any other part, such as ..., .hidden or docs, is the name of a folder: go into it./, has one / between folders, and has no / at the end, except that the root itself is /.Input: path = "/home//docs/./old/../new/"
Output: "/home/docs/new"Split the path at the slashes and read the parts from left to right. A stack holds the folder names you are inside, from the root down. A name goes on the stack, and .. takes the last one off.
| Part | What it is | Action | Stack after |
|---|---|---|---|
| (empty) | empty (before the leading slash) | skip | (empty) |
home |
a name | push | home |
| (empty) | empty (doubled or trailing slash) | skip | home |
docs |
a name | push | home, docs |
. |
here | skip | home, docs |
old |
a name | push | home, docs, old |
.. |
up one level | pop old |
home, docs |
new |
a name | push | home, docs, new |
| (empty) | empty (doubled or trailing slash) | skip | home, docs, new |
The stack ends as home, docs, new, so the path is /home/docs/new.
Input: path = "/../.."
Output: "/"Both parts are .. and the stack is empty, so nothing happens. The result is the root.
Input: path = "/a/.../b/"
Output: "/a/.../b"Only . and .. are special. Three dots make a name, so ... is a folder, and the path keeps it.
1 ≤ length of path ≤ 10^5path starts with / and uses only the letters a to z, dots and /A plan that scans from the left for every .. is slow when a long run of names is followed by many ... It costs about 3 × 10^8 steps for 100,000 characters.
So the work must be close to n steps in all. Each part should be handled once, as you read it from the left.