Skip to content

Instantly share code, notes, and snippets.

@ssshukla26
Created September 7, 2021 15:51
Show Gist options
  • Save ssshukla26/c3fe5b29330830f3d5b45151790ccb91 to your computer and use it in GitHub Desktop.
Save ssshukla26/c3fe5b29330830f3d5b45151790ccb91 to your computer and use it in GitHub Desktop.
Given a string path, which is an absolute path to a file or directory in a Unix-style file system, convert it to the simplified canonical path. [LeetCode 71]
class Solution:
def simplifyPath(self, path: str) -> str:
# Reconstuct path to suit the logic
# The curx is to maintain "/" at the end
# of the path, and the logic revolve around
# it.
# Add "/" to last if not already there
if path[-1] != "/":
path = path + "/"
# Convert /./ to /
while path.find("/./") != -1:
path = path.replace("/./","/")
# Convert // to /
while path.find("//") != -1:
path = path.replace("//","/")
# Add "/" to last if not already there
if path[-1] != "/":
path = path + "/"
# Get directories in stack
stack = []
n = len(path)
curr = ""
i = 0
# Loop till end of the path
while i < n:
# If "/" encountere either one the below case are possbile
# Case 1: It's a directory, in that case, add to stack
# Case 2: It's a "..", in that case, pop from stack
if path[i] == "/":
# IF something in curr, then it make sense to
# add or pop, else ignore
if curr:
# If it's ".." and if there is/are directory/ies in stack,
# pop latest directory from stack
if curr == ".." and stack:
stack.pop()
# If it's not "..", then it's a directory,
# add that directory into stack
elif curr != "..":
stack.append(curr)
# else do nothing
else:
pass
# reset/clear the curr
curr = ""
else: # Keep on adding characters to curr
curr = curr + path[i]
# Increment index
i += 1
# Make canonical path
res = "/"
while stack:
res = res + stack.pop(0) + "/"
# Remove last /
if len(res) > 1 and res[-1] == "/":
res = res[:-1]
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment