Problem
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Example 4:
1 | |
Example 5:
1 | |
Example 6:
1 | |
Explanation
-
First, we can split the input string by
"/". Then we can create a stack, iterate the array, if we see..then we pop, otherwise we push the name of the directory to the stack. -
Special case is when we see the
.or empty string, we ignore it. And at the end, the most inside directory name is at the top of the stack.
Solution
1 | |