Why it works
- The stack is the path so far: the folders from the root down to where we stand. Going into a folder pushes it, and ".." leaves the folder entered last, which is the top.
- Empty parts and "." do not move us, so they are skipped. ".." at the root has nothing to pop and is skipped too: above the root is still the root.
- Only folder names reach the stack, so joining it with "/" gives the shortest path, with no doubled slash and none at the end.
Complexity
Time O(n) for a path of n characters: the split and the join each read it once, and each part is pushed or popped at most once. Memory O(n) for the parts and the stack.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗