[Leetcode][71. Simplify Path] Stack Solution with Easy Detailed Explanation
By Long Luo
This article is the solution Stack Solution with Easy Detailed Explanation of Problem 71. Simplify Path .
Intuition
We can just simulate the process from the begin to end.
First we split the given string \(\textit{path}\) into a list of strings by the slash \(/\), denoted as names
. According to the canonical path in the problem description, the strings contained in names
can only be the following:
- empty string;
- a dot
.
; - two dots
..
; - a directory name containing only English letters, numbers, or
_
.
If we meet empty string or .
, we can ignore them because empty string means nothing, and .
means the current directory itself, so we don’t need to change directories.
If we meet ..
or “directory names”, we can use a Stack to maintain each directory name in the path. When we encounter “two dots”, we need to change the directory to the parent directory. As the stack is not empty, we pop the directory of the stack. When we encounter a “directory”, we put it to the stack.
Finally we need to iterate each string in names
and do the above. After all operations are completed, we connect the strings from the bottom of the stack to the top of the stack with /
, and then add /
at the top to indicate the root directory, and we can get the simplified Canonical path.
1 | class Solution { |
1 | class Solution: |
1 | func simplifyPath(path string) string { |
Analysis
- Time Complexity: \(O(N)\) .
- Space Complexity: \(O(N)\) .
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗