classSolution: defsimplifyPath(self, path: str) -> str: path = path.split("/") path = [p for p in path iflen(p)] # print(path) stack = list() # stack.append("/") for p in path: if p == ".": continue if p == "..": ifnot stack: continue stack.pop() else: # print("--",p) stack.append(p) # print('-------') return"/"+"/".join(stack)
一种更简洁的写法:
1 2 3 4 5 6 7 8 9
classSolution: defsimplifyPath(self, path: str) -> str: stack = list() for p in path.split("/"): if p in [".","..",""]: if p== ".."and stack: stack.pop() else: stack.append(p) return"/"+"/".join(stack)