Back to course home
0% completed
Vote For New Content
Solution without splitting. this is more proper
Mohammed Dh Abbas
Jul 26, 2024
class Solution: def simplifyPath(self, path): stack = [] i = 0 temp = [] # for accumulating sub path characters like "foo/home". it stores foo and home while i < len(path): # if we have perviously accumulated path push it to the stack if path[i] == "/" and len(temp) > 0: stack.append(''.join(temp)) temp = [] # ".." case. pop the previous element elif path[i] == "." and len(stack) > 0 and stack[-1] == '.': stack.pop() if len(stack) > 0: stack.pop() # "/." case. pop the "." elif path[i] == "/" and len(stack) > 0 and stack[-1] == '.': stack.pop() # accumulate anything not ". or /" elif path[i] != '/' and path[i] != '.': temp.append(path[i]) # "." case push the "." elif path[i] == '.': stack.append(path[i]) i += 1 # left over path to be appended if len(temp) > 0: stack.append(''.join(temp)) # last char is a . just remove it elif len(stack) > 0 and stack[-1] == '.': stack.pop() return '/' + '/'.join(stack)
0
0
Comments
Comments
On this page