LC 0071 [M] Simplify Path - ALawliet/algorithms GitHub Wiki
`path.split('/')` translates '/' -> '' and handles '//' -> '/'
'//' and start and end '/' get included as '', but not the ones in between
"/a/../../b/../c//.//"
['', 'a', '..', '..', 'b', '..', 'c', '', '.', '', '']
class Solution:
def simplifyPath(self, path: str) -> str:
# Initialize a stack
dirs = []
# Split the input string on '/' as the delimiter
# and process each portion one by one
for token in path.split('/'):
if not token or token == '.': # // or /./
# A no-op for a '.' or an empty string
continue
# If the current component is a '..', then we pop an entry from the stack if it's non-empty
elif token == '..':
if dirs:
dirs.pop()
else:
# Finally, a legitimate directory name, so we add it
# to our stack
dirs.append(token)
# Prepend a / and stitch together all the directory names togethe
return '/' + '/'.join(dirs)