Simplify Path

这题要求简化unix的文件路径,其中有两种特殊字符需要考虑,

  • '.'代表停留在当前路径
  • '..'代表返回上层路径

同时这里提示了双斜杠的特殊输入要规范化,下面上一个最短也很容易理解的代码,自己的代码还是太长而且逻辑不简洁

class Solution(object):
    def simplifyPath(self, path):
        places = [p for p in path.split("/") if p != "." and p != ""]     # 把所有斜杠全部丢掉,然后再把得到的里面的单点和空串丢掉
        stack = []
        for p in places:
            if p == "..":                    # 双点代表stack里面有一个路径不需要记录
                if stack:
                    stack.pop()
            else:
                stack.append(p)
        return "/" + "/".join(stack)

results matching ""

    No results matching ""