By Long Luo

# 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:

1. empty string;
2. a dot .;
3. two dots ..;
4. 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.

## 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. 😉😃💗