Simplify Path
MediumStack · Airbnb
You are given an absolute Unix-style file path path (it always starts with /). Return its canonical form.
Split the path on / and interpret each piece:
- An empty piece (from repeated slashes like
//) or.means "stay in the current directory" and is ignored. ..means "go up to the parent directory". Going up from the root/does nothing.- Anything else is a directory name, including names made only of periods such as
...or.....
The canonical path:
- starts with a single
/, - has exactly one
/between directory names, - does not end with
/(unless the whole path is just/), - contains no
.or..pieces.
Example 1
- Input:
- path = "/x/y/z/../../w/"
- Output:
- "/x/w"
- Explanation
- The two
..pieces leavezand theny, sowends up directly under/x. The trailing slash is dropped.
Example 2
- Input:
- path = "/../.../a//./"
- Output:
- "/.../a"
- Explanation
- The first
..is at the root and does nothing....is an ordinary directory name, the double slash collapses, and.is ignored.
Example 3
- Input:
- path = "/p/q/../../../r"
- Output:
- "/r"
- Explanation
- Two
..pieces climb back to the root, and the third one has nowhere further to go, so the result is/r.
Constraints
- 1 ≤
path.length≤ 3000 pathconsists of English letters, digits,.,/, and_pathis a valid absolute Unix path (it starts with/)