Given a string
In a Unix-style file system, a period
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.
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Constraints:
1 <= path.length <= 3000 path consists of English letters, digits, period'.' , slash'/' or'_' .path is a valid absolute Unix path
Contents
Solution 1 - Using a stack and read character by character from path Solution 2 - Using a stack and split the path string by '/'
In this approach, we will read character by character and construct the path element, when we see
-
First, declare two variables
stack , aStack that we will use to store path elements, andcurrent aSting to store current path element. -
Next, loop through each character of
path string and if current character is/ or if we reach of end ofpath do the following :-
If the
current value is.. , and if thestack is not empty, then remove the top the element ofstack and continue. -
If the
current value is not empty, and if it is NOT equal to. , then add thecurrent path element intostack . -
Reset the
path to"" to empty, once we either do one of the above two steps.
-
If the
-
If the current character is not
/ , then append the character tocurrent string. -
At the end, loop through
stack elements, and create a new String with'/' separator.
Complexity Analysis:
Time complexity: All the above operations runs in O(n) where
Space complexity: O(n) for storing elements into stack.
In this approach, we will same approach as above, but instead of iterating through each character, we will use utility method
Complexity Analysis:
Time complexity: All the above operations runs in O(n) where
Space complexity: O(n) for storing elements into stack.
Above implementations source code can be found at