Intuition
Split path by /, use a stack to push or pop elements.
Approach
Split the absolute path by ‘/’.
For each element
- If it’s empty, skip
- If it’s
., skip - If it’s
..and the stack has element, pop - Else push to the stack
Concat everything and return
Complexity
-
Time complexity: O(n)
-
Space complexity: O(n)
Code
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
dirs = []
for d in split(path, "/"):
if len(d) == 0:
continue
if d == ".":
continue
if d == "..":
if len(dirs) > 0:
dirs.pop()
else:
dirs.append(d)
return "/" + "/".join(dirs)