Problem
Given an absolute path for a file (Unix-style), simplify it.
OR
Given a string path
, which is an absolute path (starting with a slash '/'
) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period '.'
refers to the current directory, a double period '..'
refers to the directory up a level, and any multiple consecutive slashes (i.e. '//'
) are treated as a single slash '/'
. For this problem, any other format of periods such as '...'
are treated as file/directory names.
The canonical path should have the following format:
- The path starts with a single slash
'/'
. - Any two directories are separated by a single slash
'/'
. - The path does not end with a trailing
'/'
. - The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period
'.'
or double period'..'
)
Return the simplified canonical path.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Example 4:
|
|
Example 5:
|
|
Solution
Method 1 - Using Stack and String Split Function
Looking at examples, we can see that the simplification process can be effectively managed using a stack due to the '..'
operator:
- When encountering a file or directory name, push it onto the stack.
- When encountering
'.'
, do nothing. - When encountering
'..'
, pop the top element from the stack (if any), as it signifies moving up to the parent directory. - Ignore multiple consecutive slashes, treating them as a single
'/'
.
After traversing the entire string, the elements left in the stack form the simplified absolute path. To obtain the final result, we need to reverse these elements and concatenate them into a string.
So, the algorithm is:
- Split the given path using
'/'
as the delimiter. - Use a stack to manage the folders and files.
- Traverse the split elements:
- Push valid directory names onto the stack.
- Ignore
'.'
and empty strings. - Pop the stack when encountering
'..'
.
- Construct the canonical path from the stack contents.
Code
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the input path, due to the traversal and operations on the stack. - 🧺 Space complexity:
O(n)
for storing elements in the stack.