71. Simplify Path
You are handed a string path — an absolute path in a Unix-style file system, so it always begins with a slash /. Return the canonical form of that path as a string.
A canonical path obeys these rules:
- exactly one
/separates consecutive directory names, - it never ends with a
/(unless the entire path is just the root/), - the component
.means "stay here" and vanishes, - the component
..climbs one directory up — and climbing while already at the root does nothing, - every other component is a real directory name and is kept, including names built only of dots such as
...or.....
So "/a/./b/../c//" collapses to "/a/c".
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: The trailing slash is dropped; the single directory name stays.
Example 2:
Input: path = "/a/./b/../../c/"
Output: "/c"
Explanation: `.` contributes nothing, and each `..` erases the directory committed just before it — first `b`, then `a` — leaving only `c`.
Example 3:
Input: path = "/.../deep//dir/.."
Output: "/.../deep"
Explanation: `...` is a legitimate directory name (only `.` and `..` are special). The doubled slash is squashed and the final `..` removes `dir`.
Constraints:
- 1 ≤ path.length ≤ 3000
- path consists of English letters, digits, '.', '/' and '_'
- path is a valid absolute path (it begins with '/')
Hints:
Cut the path apart at every '/'. Empty pieces (from doubled slashes) and '.' pieces can be thrown away immediately — only real names and '..' matter.
Keep a stack of directory names you have committed to so far. A normal name gets pushed; '..' pops the top if the stack is non-empty (popping an empty stack = already at root, do nothing). The answer is '/' + the survivors joined by '/'.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: path = "/home/"
Expected output: "/home"