Tidy up a file path
Simplify a file path with dots and double dots by keeping the folders you are inside on a stack, popping one for each step back up. About 12 minutes.
Where you are is a stack
A path describes a walk through folders. Split it at the slashes into pieces. The example path gives: home, an empty piece, foo, two dots, bar, and another empty piece. Each piece is a step.
A folder name goes one level deeper, so push it. Two dots mean go up one level, so pop. An empty piece or a single dot means stay where you are, so do nothing.
parts = "/a//b/".split("/")
# ["", "a", "", "b", ""]home is a folder. Push it. Stack: home.
Build the answer from the stack
Two dots at the very top level have nowhere to go, so they are ignored: only pop when the stack is not empty.
When all the pieces are done, the stack holds the folders from the root to where you ended. Join them with slashes and put one slash at the front. If the stack is empty, the answer is just the root, a single slash.
stack = ["home", "bar"] path = "/" + "/".join(stack) # "/home/bar"
What is the simplified form of /a/./b/../../c/?
- A/c
- B/a/c
- C/
Show the answer
/c. Into a, into b, back out of b, back out of a, then into c.
Simplify path
You are given an absolute path for a Unix-style file system, starting with a slash. A single dot means the current folder, two dots mean go up one folder (stepping up from the root stays at the root), and multiple slashes in a row count as one. Return the simplified canonical path: it starts with a slash, folders are separated by a single slash, there is no trailing slash (unless it is the root), and it has no dots standing for the current or parent folder.
path = "/home//foo/../bar/" → "/home/bar"
1 ≤ length of path ≤ 3,000 · path has letters, digits, . _ - and / · it starts with /