Problem
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
Algorithm
Simulation, record the depth of each name. If there is a “…” move to above. If there is a “.” ignore it.
Code
class Solution:
def simplifyPath(self, path: str) -> str:
index = []
path += '/'
sLen = len(path)
for i in range(sLen):
if path[i] == '/':
index.append(i)
deep = 0
name = []
for i in range(len(index)-1):
start = index[i]
finish = index[i+1]
if finish == start + 1:
pass
elif finish == start + 2 and path[start+1] == '.':
pass
elif finish == start + 3 and path[start+1] == '.' and path[start+2] == '.':
if name:
name.pop()
else:
name.append(path[start+1:finish])
out = ""
for i in range(len(name)):
out += "/" + name[i]
if out == "":
out = "/"
return out